首页 > 解决方案 > 如何在 UIImageView 上放置抖动动画

问题描述

我正在尝试在 UIImageView 上添加永久摇动动画。我怎样才能控制它的动画时间。

 var coffeeImageView = UIImageView(image: UIImage(named: "coffee.png"))
        shakeImg.frame = CGRectMake(100, self.view.frame.size.height - 100, 50, 50)
        self.view.addSubview(coffeeImageView)

        let coffeeShakeAnimation = CABasicAnimation(keyPath: "position")
        coffeeShakeAnimation.duration = 0.07
        coffeeShakeAnimation.repeatCount = 20
        coffeeShakeAnimation.autoreverses = true
        coffeeShakeAnimation.fromValue = NSValue(cgPoint: CGPointMake(shakeImg.center.x - 10, shakeImg.center.y))
        coffeeShakeAnimation.toValue = NSValue(cgPoint: CGPointMake(shakeImg.center.x + 10, shakeImg.center.y))
        shakeImg.layer.add(coffeeShakeAnimation, forKey: "position")

标签: swiftanimationuiimage

解决方案


你需要

var coffeeImageView = UIImageView(image: UIImage(named: "coffee.png"))
coffeeImageView.frame = CGRect(x: 100, y: self.view.frame.size.height - 100, width: 50, height: 50)
self.view.addSubview(coffeeImageView) 
let coffeeShakeAnimation = CABasicAnimation(keyPath: "position")
coffeeShakeAnimation.duration = 0.07
coffeeShakeAnimation.repeatCount = 20
coffeeShakeAnimation.autoreverses = true
coffeeShakeAnimation.fromValue = NSValue(cgPoint: CGPoint(x: coffeeImageView.center.x - 10, y: coffeeImageView.center.y))
coffeeShakeAnimation.toValue = NSValue(cgPoint: CGPoint(x: coffeeImageView.center.x + 10, y: coffeeImageView.center.y))
coffeeImageView.layer.add(coffeeShakeAnimation, forKey: "position")

extension UIView {
    func shake(_ dur:Double) {
        let anim = CABasicAnimation(keyPath: "position")
        anim.duration = dur
        anim.repeatCount = 20
        anim.autoreverses = true
        anim.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y))
        anim.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 10, y: self.center.y))
        self.layer.add(anim, forKey: "position")
    }
}

在此处输入图像描述


推荐阅读