制作动画以扩展和缩小UIView

时间:2014-03-14 03:44:35

标签: ios cocoa-touch caanimation

我想创建一个动画,它将通过一个因子调整UIView及其内容的大小。基本上,我想制作一个动画,首先展开视图,然后将其缩小回原始大小。

最好的方法是什么?我尝试了CALayer.contentScale,但它根本没有做任何事情。

3 个答案:

答案 0 :(得分:51)

您可以像这样嵌套一些动画块:

目标-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
        })}
斯威夫特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
    })
}

并用您自己的比例替换比例值和持续时间。

答案 1 :(得分:10)

这是一个较小的方法,也循环:

[UIView animateWithDuration:1
                      delay:0
                    options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat
                 animations:^{
                     yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
                 }
                 completion:nil];

选项UIViewKeyframeAnimationOptionRepeat是让它循环的原因,如果你不希望它保持“呼吸”。动画块充当“吸气”,UIViewKeyframeAnimationOptionAutoreverse选项自动播放“呼气”动画。

答案 2 :(得分:1)

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