iOS实现仿抖音直播头像动画
2018-08-24 本文已影响1172人
QYiZHong
最近公司有一个需求就是做一个类似抖音直播头像的头像动画。先放上效果
animation.gif
如果这个圈是单一颜色的话那这个需求其实是很好实现的,用plulsing就行了。但是我们的需求之中,这个圈的颜色得是渐变的。那这里就涉及了CAGradientLayer、CAShapeLayer以及mask,就变得麻烦了。但是这只有两个圈也就是说可以放两个用mask遮盖的view,其中一个view的layer和头像的layer做scale就可以做到这个效果了。
首先显示写一个渐变的layer吧
- (CAGradientLayer *)backgroudLayer {
CAGradientLayer *gLayer = [CAGradientLayer layer];
gLayer.frame = self.bounds;
[gLayer setColors:@[(id)[UIColorFromRGB(0xbe4ff6) CGColor], (id)[UIColorFromRGB(0xff3366) CGColor]]];
[gLayer setLocations:@[@0.0, @1.0]];
[gLayer setStartPoint:CGPointMake(0.0, 0.0)];
[gLayer setEndPoint:CGPointMake(1.0, 1.0)];
return gLayer;
}
UIColorFromRGB是用来实现16进制rgb的宏,这里提供一下
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
这个渐变的layer需要变成一个渐变的圈,那么用mask就行,先写一个mask的layer
- (CAShapeLayer *)maskLayerWithRadius:(CGFloat)radius lineWidth:(CGFloat)lineWidth {
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:self.center radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.fillColor = [UIColor clearColor].CGColor;
maskLayer.strokeColor = [UIColor whiteColor].CGColor;
maskLayer.lineWidth = lineWidth;
maskLayer.path = path.CGPath;
return maskLayer;
}
所以后这个头像的渐变边框是
CAGradientLayer *gLayer = [self backgroudLayer];
CAShapeLayer *maskLayer = [self maskLayerWithRadius:radius - 9 lineWidth:2];
gLayer.mask = maskLayer;
[self.layer addSublayer:gLayer];
头像外面还有一个细一点的圈,那就再盖一个view做
CAGradientLayer *scaleLayer = [self backgroudLayer];
CAShapeLayer *scaleMaskLayer = [self maskLayerWithRadius:radius - 9 lineWidth:0.8];
scaleLayer.mask = scaleMaskLayer;
[self.scaleView.layer addSublayer:scaleLayer];
然后在用写上头像和外面细圈的动画
- (CAKeyframeAnimation *)avatarScaleAnimation {
CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.values = @[@0.889, @0.950, @1.05, @1.125, @1.05, @0.950, @0.889];
scaleAnimation.repeatCount = MAXFLOAT;
scaleAnimation.duration = 1.0;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
return scaleAnimation;
}
- (CAKeyframeAnimation *)bottomScaleAnimation {
CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.values = @[@0.97,@1.0, @1.03, @1.06, @1.09, @1.12];
scaleAnimation.repeatCount = MAXFLOAT;
scaleAnimation.duration = 1.0;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
return scaleAnimation;
}
最后加上动画
- (void)addAnimation {
[self.avatarImageView.layer addAnimation:[self avatarScaleAnimation] forKey:@"avatar_scale"];
[self.scaleView.layer addAnimation:[self bottomScaleAnimation] forKey:@"bottom_scale"];
}