ios - Swift:动画拉伸(stretch)和收缩图像

标签 ios swift xcode animation

我正在尝试在我的应用程序中为光剑的拉伸(stretch)和收缩设置动画。目前,除了光剑的拉伸(stretch)/收缩之外,我的一切都在工作。

理想情况下,我希望能够使实际军刀的底部 anchor 齐平于刀柄顶部 anchor 的下方。我已经能够通过自动布局约束取得一些不错的成绩。但是,我正在努力寻找合适的动画代码。正如您从我的代码中看到的那样,我尝试了 frame.size.height/width,但是这只会移动军刀的框架(而不是 handle )。带有 frame.size.height 的行在使其拉伸(stretch)/增长方面实现了我想要的,但这是一种非常盗版的方式。

当前的 frame.size.height/width 方法只是移动图像,我如何实现拉伸(stretch)/收缩功能?是否可以通过 Auto Layout constraints 的 multiplier 函数来实现?

@objc func lightsaberTapped() {
    print("lightsaber open!")

    if mainView.saberImage.isHidden == true {
        mainView.saberImage.isHidden = false
        UIView.animate(withDuration: 0.5, animations: {

            self.mainView.saberImage.frame.size.height -= 500
//          self.mainView.saberImage.frame.size.width += 20

            }, completion: nil)
        lightsaberModel.turnSaberOnAudio.play()
    } else {
        mainView.saberImage.isHidden = true
        UIView.animate(withDuration: 0.5, animations: {

            self.mainView.saberImage.frame.size.height += 500
//          self.mainView.saberImage.frame.size.width += 20

        }, completion: nil)
    }
}

最佳答案

你的主要问题是框架动画,而你有约束,你需要 2 个中的 1 个或动画约束或删除它并使用框架属性设置动画,在这种情况下你需要确保你的 UIImageView添加了 translatesAutoresizingMaskIntoConstraints = false

要在 Autolayout 系统中设置宽度和高度的动画,您需要获取作为 IBOutlet 的约束引用,并在动画 block 中设置常量属性,

这是一个非常小的例子

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    }
    @IBAction func action(_ sender: Any) {
        UIView.animate(withDuration: 0.5, animations: {
            self.imageHeightConstraint.constant = self.imageHeightConstraint.constant - 10
            self.imageWidthConstraint.constant = self.imageWidthConstraint.constant - 10
            self.view.layoutIfNeeded()
        })
    }

}

关于ios - Swift:动画拉伸(stretch)和收缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052921/

相关文章:

c - Xcode 返回 (lldb),同时运行 C 应用程序

ios - VOIP 服务证书的用途是什么?

ios - 更新 UITabBarController 的所有 View Controller

swift - Vapor 3解码内容: do/catch for multiple post formats?

ios - 联盟控制州

ios - 如何使用 Storyboard 重新排列 UITabBarController 项目?

ios - 如何比较数组中的 UIImages?

ios - 检查单击了哪个 UIAlertVeiw

swift - 尝试比较字符串数字

Xcode- 将数据存储在 Core Data 或 SQLite 中?