如何在iOS上为UIButton实现本地“脉冲效果”动画

90

我希望能在UIButton上实现一种脉冲动画(无限循环“放大 - 缩小”),以便立即引起用户注意。

我看到了这个链接如何使用-webkit动画创建脉冲效果 - 外向环,但我想知道是否有任何方法只使用本地框架来实现此目的?

4个回答

200
CABasicAnimation *theAnimation;

theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=1.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];
[theLayer addAnimation:theAnimation forKey:@"animateOpacity"]; //myButton.layer instead of

Swift

let pulseAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
pulseAnimation.duration = 1
pulseAnimation.fromValue = 0
pulseAnimation.toValue = 1
pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = .greatestFiniteMagnitude
view.layer.add(pulseAnimation, forKey: "animateOpacity")

查看文章《Animating Layer Content》


1
谢谢你的回答!不过我必须说我有点卡住了。我对CALayer一点也不熟悉,也不确定如何将其与我的UIButton链接起来。此外,你的代码似乎是在改变透明度,而不是比例。 - Johann
8
“脉冲动画”通常是用于描述闪烁效果的术语-正如链接中所说的例子。现在我重新阅读了您的问题并理解了您的意图。首先,每个视图都有自己的层。如果将QuartzCore框架添加到项目中,则只需键入myView.layer即可访问它。您可以使用核心动画来对层进行动画处理。对于缩放变换,您可以使用此方法:结构字段的关键路径支持 - beryllium
7
太棒了!使用@"transform.scale"而不是@"opacity"非常有效。非常感谢! - Johann
2
如果您还没有它,您需要添加#import <QuartzCore/QuartzCore.h>以获取CALayer的所有定义。 - progrmr
不要编辑已经过时的三年前的答案,除非你正在将实际答案更新为正确的现代版本。添加空格并不是更新它。特别是不要在三年后重新激活它。 - Fogmeister
显示剩余6条评论

32

这是它的 Swift 代码;)

let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 1.0
pulseAnimation.fromValue = NSNumber(value: 0.0)
pulseAnimation.toValue = NSNumber(value: 1.0)
pulseAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = .greatestFiniteMagnitude
self.view.layer.add(pulseAnimation, forKey: nil)

2
所有这些分号是怎么回事? ;) - Christian
@Christian 分号设置了 pulseAnimation 常量的类型。虽然不是必须的,但当赋值语句的右侧不明确指定类型时,使用分号可以提高代码的清晰度。 - Scott Chow
@ScottChow 我猜你在谈论冒号。我的评论是对原始答案的一个玩笑,因为在Swift中不需要分号。现在答案已经被编辑了很多,所以可能不是那么明显了 :) - Christian
请添加一个 fromValue。 - Kev Wats

10

Swift代码缺少fromValue,我不得不添加它以使其正常工作。

pulseAnimation.fromValue = NSNumber(value: 0.0)

同时需要设置forKey,否则removeAnimation不起作用。

self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")

4
func animationScaleEffect(view:UIView,animationTime:Float)
{
    UIView.animateWithDuration(NSTimeInterval(animationTime), animations: {

        view.transform = CGAffineTransformMakeScale(0.6, 0.6)

        },completion:{completion in
            UIView.animateWithDuration(NSTimeInterval(animationTime), animations: { () -> Void in

                view.transform = CGAffineTransformMakeScale(1, 1)
            })
    })

}


@IBOutlet weak var perform: UIButton!

@IBAction func prefo(sender: AnyObject) {
    self.animationScaleEffect(perform, animationTime: 0.7)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接