swift - 如何在 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")
解决方案
你需要
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")
}
}
推荐阅读
- python - 这个循环不像我想要的那样循环。我希望它循环直到有有效的输入
- python - for循环没有在python中执行
- laravel - 在 Eloquent 集合中首先放置一个对象
- c++ - Visual Studio 无法识别 __AVX2__ 或 __AVX__
- c++ - 对 C++ 向量进行排序
- azure-ad-b2c - 如何使用图形 api 在 AAD B2C 中创建具有自定义属性的用户
- php - 为什么这个带参数的 sqlsrv 查询不起作用?
- c# - 根据路径使用 OAuth 和 ADFS 进行 ASP.Net 身份验证
- asp.net-mvc - 从 CMS.File 页面类型中检索二进制数据
- python-3.x - 通过另一种方法退出 lambda 表达式