ios - 如何在UIButton上执行本机"脉冲效果"动画

Joh*_*ann 87 animation objective-c uikit ios

我希望在UIButton上有一些脉冲动画(无限循环"缩放 - 缩小"),以便立即引起用户的注意.

我看到了这个链接如何使用-webkit-animation创建脉冲效果 - 外向环但我想知道是否有任何方法只使用本机框架来做到这一点?

任何帮助非常感谢 - 代码示例甚至更好;-)

ber*_*ium 194

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
Run Code Online (Sandbox Code Playgroud)

迅速

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")
Run Code Online (Sandbox Code Playgroud)

看到这篇文章

  • 不要忘记将QartzCore框架添加到您的项目中 (13认同)
  • 好的)."脉冲动画"是一个通常用于闪烁效果的术语 - 如该链接中的示例所述.现在我重新阅读你的问题并理解你想要的东西.首先,每个视图都有自己的图层.如果将QartzCore框架添加到项目中,则只需键入`myView.layer`即可访问它.您可以使用Core Animation为图层设置动画.对于比例转换,您可以使用以下方法:[结构字段的关键路径支持](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/KVCAdditions.html#//apple_ref/ DOC/UID/TP40005299-SW6) (8认同)
  • 太棒了!使用@"transform.scale"代替@"opacity"就像魅力一样.非常感谢! (7认同)
  • 如果您还没有它,则需要添加`#import <QuartzCore/QuartzCore.h>`以获取CALayers的所有定义. (2认同)

Rav*_*rma 29

这是它的快速代码;)

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

  • 所有的冒号是什么?;) (2认同)

Bas*_*bus 9

快速代码缺少一个fromValue,我不得不添加它以使其工作.

pulseAnimation.fromValue = NSNumber(float: 0.0)
Run Code Online (Sandbox Code Playgroud)

forKey应该设置,否则removeAnimation不起作用.

self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")
Run Code Online (Sandbox Code Playgroud)