先看下最后基本要實現的效果
總結一下自己的實現思路與所用到的類
1.這個肯定是要自定義的View類,起名為XDColorCircle吧文虏,最后用的時候達到這樣的效果
//創(chuàng)建XDColorCircle的實例化對象
XDColorCircle *circle=[[XDColorCircle alloc]initWithFrame:CGRectMake(0 ,100,self.view.frame.size.width,200)];
//添加到視圖上展示
[self.view addSubview:circle];
2.然后就是在XDColorCircle里面代碼思路
- 需要先有一個漸變的圖層(漸變由白到靛)且圖層需只顯示一個圓圈形狀
- 漸變圖層用CAGradientLayer這個類繪制
- 為這個CAGradientLayer的mask賦值一個圓圈的圖層讓它只展示一個圓圈CAShapeLayer
- 為CAGradientLayer圖層添加基礎動畫就用CABasicAnimation來實現圖層的旋轉
- 中間需要一個大Label但肯定這個Label不能繪制在這個CAGradientLayer所在的圖層之上了节视,因這個圖層設置mask了 怎么繪制都顯示個圈 ╮( ̄▽ ̄"")╭
- 所以最后確定了圈圈應該在另創(chuàng)建一個View上繪制然后與中間的Label一同做為XDColorCircle的子視圖
3.思路捋順代碼就很方便
//先都寫在這個構造方法里面吧
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
創(chuàng)建圈圈所在的View
self.backgroundColor=[UIColor clearColor];
UIView *circleView=[[UIView alloc]init];
circleView.frame=CGRectMake(0, 0,frame.size.width,frame.size.height);
circleView.backgroundColor=[UIColor blueColor];
[self addSubview: circleView];
創(chuàng)建漸變圖層并添加到圈圈視圖
CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor,(__bridge id)[UIColor cyanColor].CGColor];
gradientLayer.locations = @[@0.2,@1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame =CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[circleView.layer insertSublayer:_gradientLayer atIndex:0];
添加mask屬性只讓圖層只顯示一個圈圈
CAShapeLayer *layer=[[CAShapeLayer alloc]init];
CGMutablePathRef pathRef=CGPathCreateMutable();
CGPathAddRelativeArc(pathRef, nil,frame.size.width/2.0,frame.size.height/2.0,frame.size.width<frame.size.height?frame.size.width/2.0-5:frame.size.height/2.0-5,0, 2*M_PI);
layer.path=pathRef;
layer.lineWidth=5;
layer.fillColor=[UIColor clearColor].CGColor;
layer.strokeColor=[UIColor blackColor].CGColor;
CGPathRelease(pathRef);
circleView.layer.mask=layer;
讓圈圈轉起來添加動畫
CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; ;
// 設定動畫選項
animation.duration = 1;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.repeatCount =HUGE_VALF;
// 設定旋轉角度
animation.fromValue = [NSNumber numberWithFloat:0.0]; // 起始角度
animation.toValue = [NSNumber numberWithFloat:2 * M_PI]; // 終止角度
[circleView.layer addAnimation:animation forKey:@"rotate-layer"];
添加中間的大文字Label
UILabel *label=[[UILabel alloc]init];
label.text=@"測試中";
label.font=[UIFont systemFontOfSize:32];
label.textAlignment=NSTextAlignmentCenter;
label.frame=CGRectMake(0, 0,frame.size.width,frame.size.height);
label.backgroundColor=[UIColor clearColor];
[self addSubview:label];
4.然后在controller里面使用
//創(chuàng)建XDColorCircle的實例化對象
XDColorCircle *circle=[[XDColorCircle alloc]initWithFrame:CGRectMake(0 ,100,self.view.frame.size.width,200)];
//添加到視圖上展示
[self.view addSubview:circle];
#######只是個簡單的動畫實現小例子,可以看出活用CAShapeLayer和CABasicAnimation可以做出更炫的動畫效果