脉冲动画, 就是类似一个圆圈向外扩散的效果,多用于搜索场景
一: 实现思路:
脉冲动画,实质上可以把扩散的圆圈看成一个CALayer, 那么我们只要在这个CALayer上做动画即可
二: 实现过程
-
1: 首先我们先创建一个类CCJHaloLayer,继承于CALayer,radius半径,
@interface CCJHaloLayer, : CALayer @property (nonatomic, assign) CGFloat radius; @property (nonatomic, assign) NSTimeInterval animationDuration; @property (nonatomic, assign) NSTimeInterval pulseInterval; @end
-
2:当然在进一步做动画前,我们要在类的开头,导入QuartzCore等框架并生成一个动画组作为属性
#import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @interface CCJHaloLayer () @property (nonatomic, strong) CAAnimationGroup *animationGroup; @end
-
3: .m文件中的代码
@implementation CCJHaloLayer - (id)init { self = [super init]; if (self) { self.contentsScale = [UIScreen mainScreen].scale; self.opacity = 0; self.radius = 200; self.animationDuration = 1.5; self.pulseInterval = 0; self.backgroundColor = [[UIColor colorWithRed:0.000 green:0.478 blue:1.000 alpha:1] CGColor]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { [self setupAnimationGroup]; if(self.pulseInterval != INFINITY) { dispatch_async(dispatch_get_main_queue(), ^(void) { [self addAnimation:self.animationGroup forKey:@"pulse"]; }); } }); } return self; } - (void)setRadius:(CGFloat)radius { _radius = radius; CGPoint tempPos = self.position; CGFloat diameter = self.radius * 2; self.bounds = CGRectMake(0, 0, diameter, diameter); self.cornerRadius = self.radius; self.position = tempPos; } - (void)setupAnimationGroup { CAMediaTimingFunction *defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]; self.animationGroup = [CAAnimationGroup animation]; self.animationGroup.duration = self.animationDuration + self.pulseInterval; self.animationGroup.repeatCount = INFINITY; self.animationGroup.removedOnCompletion = NO; self.animationGroup.timingFunction = defaultCurve; CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"]; scaleAnimation.fromValue = @0.0; scaleAnimation.toValue = @1.0; scaleAnimation.duration = self.animationDuration; CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"]; opacityAnimation.duration = self.animationDuration; opacityAnimation.values = @[@0.45, @0.45, @0]; opacityAnimation.keyTimes = @[@0, @0.2, @1]; opacityAnimation.removedOnCompletion = NO; NSArray *animations = @[scaleAnimation, opacityAnimation]; self.animationGroup.animations = animations; } @end
三: 如何使用
比如所我想在点击按钮搜索的方法中进行动画,那么只需要加入如下代码即可
此处设置为动画的产生效果从按钮的中点开始, 首先为了防止重复点击,在方法的一开始就先移除以前的layer
- (IBAction)searchBtnClick:(UIButton *)sender
{
[self.halo removeFromSuperlayer];
self.halo = [CCJHaloLayer layer];
self.halo.position = sender.center;
[self.view.layer insertSublayer:self.halo below:sender.layer];
self.first = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.halo removeFromSuperlayer];
});
}
这样就可以在任何你想要的位置添加脉冲动画了