?看一下效果:
?
使用方法:
UISpinnerAnimationView *evi = [[UISpinnerAnimationView alloc] initWithFrame:CGRectMake((self.view.frame.size.width-160)/2, 160, 160, 160)];
[self.view addSubview:evi];
[evi startSpinerAnimation];
源代码:
@interface UISpinnerAnimationView : UIView
//画笔粗细,默认为6
@property (nonatomic,assign) CGFloat lineWidth;
//画笔轮廓颜色
@property (nonatomic,strong) UIColor *strokeColor;
/* An object providing the contents of the layer, typically a CGImageRef
* or an IOSurfaceRef, but may be something else. (For example, NSImage
* objects are supported on Mac OS X 10.6 and later.) Default value is nil.
* Animatable. */
@property (nonatomic,strong) UIImage *contentImage;
//动画完成时间
@property (nonatomic,assign) CGFloat aniDuration;
- (void)startSpinerAnimation;
- (void)stopSpinerAnimation;
@end
#import "UISpinnerAnimationView.h"
@implementation UISpinnerAnimationView
- (instancetype)initWithFrame:(CGRect)frame
{
if ([super initWithFrame:frame])
{
self.lineWidth = 6;
self.strokeColor = [UIColor colorWithRed:2.0/255.0 green:134.0/255.0 blue:224.0/255.0 alpha:1];
self.contentImage = [UIImage imageNamed:@"angle-mask"];
self.aniDuration = 1;
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:frame.size.width / 2];
[self.layer setBorderColor:[UIColor clearColor].CGColor];
}
return self;
}
- (void)startSpinerAnimation
{
CGFloat lineWidth = self.lineWidth;
CGPoint arcCenter = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
UIBezierPath *smoothedPath = [UIBezierPath bezierPath];
[smoothedPath addArcWithCenter:arcCenter radius:self.frame.size.width / 2 startAngle:0 endAngle:2 * M_PI clockwise:YES];
CAShapeLayer *layer = [CAShapeLayer layer];
[layer setContentsScale:UIScreen.mainScreen.scale];
[layer setFrame:CGRectMake(0, 0, arcCenter.x * 2, arcCenter.y * 2)];
[layer setFillColor:UIColor.clearColor.CGColor];
[layer setStrokeColor:self.strokeColor.CGColor];
[layer setLineWidth:lineWidth];
[layer setLineCap:kCALineCapRound];
[layer setLineJoin:kCALineJoinBevel];
[layer setPath:smoothedPath.CGPath];
[layer setMask:[CALayer layer]];
layer.mask.contents = (__bridge id _Nullable)(self.contentImage.CGImage);
[layer.mask setFrame:self.bounds];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.fromValue = [NSNumber numberWithFloat:0.0];
animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
animation.duration = self.aniDuration;
[animation setRemovedOnCompletion:NO];
animation.repeatCount = HUGE_VALF;
animation.autoreverses = NO;
[layer addAnimation:animation forKey:@"rotate"];
[self.layer addSublayer:layer];
}
- (void)stopSpinerAnimation
{
[[self.layer sublayers] enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj removeAllAnimations];
}];
}
@end
用到的资源文件:点击下载资源文件
?
|