最近项目需求,做的一个标识正在直播的小动画,代码如下:
#import "YGIsOnLiveAnmationView.h"
@interface YGIsOnLiveAnmationView ()
@property (strong, nonatomic) CAShapeLayer * progressLayer;
@property (strong, nonatomic) CAShapeLayer * triangleLayer;
@property (strong, nonatomic) CABasicAnimation *rotateAnimation;
@property (assign, nonatomic) CGFloat progressLineWidth;
@property (strong, nonatomic) UIColor * progressLineColor;
@end
@implementation YGIsOnLiveAnmationView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth lineColor:(UIColor *)lineColor {
self = [self initWithFrame:frame];
if (self) {
self.progressLineWidth = lineWidth;
self.progressLineColor = lineColor;
[self.layer addSublayer:self.progressLayer];
[self.layer addSublayer:self.triangleLayer];
}
return self;
}
- (void)startProgressAnimation {
[self.progressLayer addAnimation:self.rotateAnimation forKey:@"group"];
}
//画三角形
- (CAShapeLayer *)triangleLayer {
if (!_triangleLayer) {
_triangleLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
CGFloat X = self.center.x;
CGFloat Y = self.center.y;
[path moveToPoint :CGPointMake(X-3, Y-5)];
[path addLineToPoint:CGPointMake(X-3, Y+5)];
[path addLineToPoint:CGPointMake(X+5, Y)];
[path closePath];
[self.progressLineColor setFill];
[path fill];
_triangleLayer.path = path.CGPath;
}
return _triangleLayer;
}
//画进度
- (CAShapeLayer *)progressLayer {
if (!_progressLayer) {
_progressLayer = [CAShapeLayer layer];
CGFloat width = CGRectGetWidth(self.frame);
CGFloat height = CGRectGetHeight(self.frame);
_progressLayer.frame = CGRectMake(0, 0, width, height);
_progressLayer.position = CGPointMake(width/2.0,height/2.0);
UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2.0, height/2.0)
radius:(width - self.progressLineWidth)/2.0
startAngle:0
endAngle:M_PI_4 * 7
clockwise:YES];
[aPath stroke];
_progressLayer.path = aPath.CGPath;
_progressLayer.fillColor = [UIColor clearColor].CGColor;
_progressLayer.lineWidth = self.progressLineWidth;
_progressLayer.strokeColor = self.progressLineColor.CGColor;
_progressLayer.lineCap = kCALineCapRound;
}
return _progressLayer;
}
- (CABasicAnimation *)rotateAnimation {
if (!_rotateAnimation) {
_rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
_rotateAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
_rotateAnimation.toValue = @(M_PI * 2);
_rotateAnimation.fromValue = @(0);
_rotateAnimation.duration = 1;
_rotateAnimation.removedOnCompletion = NO;
_rotateAnimation.repeatCount = FLT_MAX;
}
return _rotateAnimation;
}
@end