iOS 雷达扩散动画,给view添加分类
2017-07-21 本文已影响272人
雪_晟
动画有点抖s
gif.gif
给UIView添加一个分类
#import <UIKit/UIKit.h>
@interface UIView (RadarAnimation)
@property(nonatomic,strong)UIColor *radarColor; //扩散颜色
@property(nonatomic,assign)UIColor *radarBorderColor; //扩散边界颜色
-(void)addRadarAnimation;
@end
调用方法:
button.radarColor = LBColor(237, 174, 130, 1);
button.radarBorderColor = LBColor(237, 174, 130, 0.5);
[button addRadarAnimation];
添加动画的方法,创建三个layer,只不过,开始动画的时间要错开形成这个效果:
-(void)Animation{
NSInteger pulsingCount = 3;
double animationDuration = 2;
CALayer * animationLayer = [[CALayer alloc]init];
for (int i = 0; i < pulsingCount; i++) {
CALayer * pulsingLayer = [[CALayer alloc]init];
pulsingLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
pulsingLayer.backgroundColor = self.radarColor.CGColor;
pulsingLayer.borderColor = self.radarBorderColor.CGColor;
pulsingLayer.borderWidth = 1.0;
pulsingLayer.cornerRadius = self.frame.size.height/2;
CAMediaTimingFunction * defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
CAAnimationGroup * animationGroup = [[CAAnimationGroup alloc]init];
animationGroup.fillMode = kCAFillModeBoth;
animationGroup.beginTime = CACurrentMediaTime() + (double)i * animationDuration/(double)pulsingCount;
animationGroup.duration = animationDuration;
animationGroup.repeatCount = HUGE_VAL;
animationGroup.timingFunction = defaultCurve;
CABasicAnimation * scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.autoreverses = NO;
scaleAnimation.fromValue = [NSNumber numberWithDouble:1];
scaleAnimation.toValue = [NSNumber numberWithDouble:1.5];
CAKeyframeAnimation * opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.values = @[[NSNumber numberWithDouble:1.0],[NSNumber numberWithDouble:0.5],[NSNumber numberWithDouble:0.3],[NSNumber numberWithDouble:0.0]];
opacityAnimation.keyTimes = @[[NSNumber numberWithDouble:0.0],[NSNumber numberWithDouble:0.25],[NSNumber numberWithDouble:0.5],[NSNumber numberWithDouble:1.0]];
animationGroup.animations = @[scaleAnimation,opacityAnimation];
[pulsingLayer addAnimation:animationGroup forKey:@"pulsing"];
[animationLayer addSublayer:pulsingLayer];
}
animationLayer.zPosition = -1;//重新加载时,使动画至底层
[self.layer addSublayer:animationLayer];
}
为了防止动画进入后台假死,需要监听通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterPlayground) name:UIApplicationDidBecomeActiveNotification object:nil];
demo 地址:漫漫的demo