swift - 我如何在 UIImageView 上放置摇动动画

标签 swift animation uiimage

我正在尝试在 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")

最佳答案

你需要

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")
    }
}

enter image description here

关于swift - 我如何在 UIImageView 上放置摇动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253401/

相关文章:

UITableView 单元格中的 iOS Swift Like 按钮

ios - UIStackView - 拖动以重新排列排列的 subview ?

swift - 如何在 SwiftUI 中给 DatePicker 一个分钟间隔

android - Android 中的动画虚线边框

python - 从 blender 导出以在 ogl 中查看的正确骨骼数据?

ios - 图像未压缩到小于 307kb。 ios9

swift - 从单个串行队列访问 Swift 实例变量导致 Thread Sanitizer 问题

jQuery 对多个元素进行动画处理,哪个更好?

ios - 在 Swift App 中从 PubNub didReceiveMessage 函数检索图像时遇到问题

ios - UIImage 未在 Unwind Segue 上更新