先看下最后基本要实现的效果
总结一下自己的实现思路与所用到的类
1.这个肯定是要自定义的View类,起名为XDColorCircle吧,最后用的时候达到这样的效果
//创建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了 怎么绘制都显示个圈 ╮( ̄▽ ̄"")╭
- 所以最后确定了圈圈应该在另创建一个View上绘制然后与中间的Label一同做为XDColorCircle的子视图
3.思路捋顺代码就很方便
//先都写在这个构造方法里面吧
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
创建圈圈所在的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];
创建渐变图层并添加到圈圈视图
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里面使用
//创建XDColorCircle的实例化对象
XDColorCircle *circle=[[XDColorCircle alloc]initWithFrame:CGRectMake(0 ,100,self.view.frame.size.width,200)];
//添加到视图上展示
[self.view addSubview:circle];
#######只是个简单的动画实现小例子,可以看出活用CAShapeLayer和CABasicAnimation可以做出更炫的动画效果