ios - how to do a native “Pulse effect” animation

2019-01-16 00:42发布

I would like to have some kind of pulse animation (infinite loop "scale in - scale out") on a UIButton so it gets users' attention immediately.

I saw this link How to create a pulse effect using -webkit-animation - outward rings but I was wondering if there was any way to do this only using native framework?

Any help much appreciated - code sample even better ;-)

4条回答
在下西门庆
2楼-- · 2019-01-16 00:59

Here is the swift code for it ;)

let pulseAnimation:CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 1.0
pulseAnimation.toValue = NSNumber(value: 1.0)
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = FLT_MAX
self.view.layer.add(pulseAnimation, forKey: nil)
查看更多
甜甜的少女心
3楼-- · 2019-01-16 01:07
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)
}
查看更多
Bombasti
4楼-- · 2019-01-16 01:12

The swift code is missing a fromValue, I had to add it in order to get it working.

pulseAnimation.fromValue = NSNumber(float: 0.0)

Also forKey should be set, otherwise removeAnimation doesn't work.

self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")
查看更多
疯言疯语
5楼-- · 2019-01-16 01:18
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")

See this article

查看更多
登录 后发表回答