我想创建一个动画,它将通过一个因子调整UIView及其内容的大小。基本上,我想制作一个动画,首先展开视图,然后将其缩小回原始大小。
做这个的最好方式是什么?我尝试过CALayer.contentScale但它根本没有做任何事情。
您可以将一些动画块嵌套在一起,如下所示:
Objective-C的:
[UIView animateWithDuration:1
animations:^{
yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
}
completion:^(BOOL finished) {
[UIView animateWithDuration:1
animations:^{
yourView.transform = CGAffineTransformIdentity;
}];
}];
斯威夫特2:
UIView.animateWithDuration(1, animations: { () -> Void in
yourView.transform = CGAffineTransformMakeScale(1.5, 1.5)
}) { (finished: Bool) -> Void in
UIView.animateWithDuration(1, animations: { () -> Void in
yourView.transform = CGAffineTransformIdentity
})}
Swift 3&4:
UIView.animate(withDuration: 1, animations: {
yourView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}) { (finished) in
UIView.animate(withDuration: 1, animations: {
yourView.transform = CGAffineTransform.identity
})
}
并用您自己的替换比例值和持续时间。
这是一个较小的方法,也循环:
[UIView animateWithDuration:1
delay:0
options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat
animations:^{
yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
}
completion:nil];
选项UIViewKeyframeAnimationOptionRepeat
是让它循环的原因,如果你不想让它保持“呼吸”。动画块充当“吸气”,UIViewKeyframeAnimationOptionAutoreverse
选项自动播放“呼气”动画。
Swift 5 UIView扩展:
extension UIView {
func pulse(withIntensity intensity: CGFloat, withDuration duration: Double, loop: Bool) {
UIView.animate(withDuration: duration, delay: 0, options: [.repeat, .autoreverse], animations: {
loop ? nil : UIView.setAnimationRepeatCount(1)
self.transform = CGAffineTransform(scaleX: intensity, y: intensity)
}) { (true) in
self.transform = CGAffineTransform.identity
}
}
}
然后使用以下内容:
yourView.pulse(withIntensity: 1.2, withDuration: 0.5, loop: true)
只需确保用自己的视图替换yourView
。