标签:property self import make nullable blog 技术 ash har
使用CAGradientLayer可以实现颜色的渐变, 我们先看下头文件
@interface CAGradientLayer : CALayer @property(nullable, copy) NSArray *colors;
//颜色渐变的数组 @property(nullable, copy) NSArray<NSNumber *> *locations;
//渐变颜色的区间分布,locations的数组长度和color一致,默认是nil,会平均分布 @property CGPoint startPoint;
//映射locations中第一个位置,用单位向量表示,比如(0,0)表示从左上角开始变化。默认值是(0.5,0.0)
@property CGPoint endPoint; //映射locations中最后一个位置,用单位向量表示,比如(1,1)表示到右下角变化结束。默认值是(0.5,1.0)
@property(copy) NSString *type; //默认值是kCAGradientLayerAxial,表示按像素均匀变化。除了默认值也无其它选项
@end
下面是我用上面的代码实现的最终效果,startPoint是(0,0),endPoint是(1,1)。
下面我们试试用这个来实现一个渐变色的圆环,
需要说明的是CAGradientLayer只能实现矩形范围内的颜色渐变, 那渐变的圆环要如何实现呢? mask 对了
首先我们创建两个挨着的矩形渐变色块, 并把两个色块添加到同一个layer
再创建一个带有圆弧形状的layer作为mask
上代码:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //创建圆弧路径 UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(50, 50) radius:45 startAngle:- 7.0 / 6 * M_PI endAngle:M_PI / 6 clockwise:YES]; //添加圆弧Layer [self.view.layer addSublayer:[self createShapeLayerWithPath:path]]; //配置左色块CAGradientLayer CAGradientLayer * leftL = [self createGradientLayerWithColors:@[(id)[UIColor redColor].CGColor,(id)[UIColor yellowColor].CGColor]]; leftL.position = CGPointMake(25, 40); //配置右色块CAGradientLayer CAGradientLayer * rightL = [self createGradientLayerWithColors:@[(id)[UIColor greenColor].CGColor,(id)[UIColor yellowColor].CGColor]]; rightL.position = CGPointMake(75, 40); //将两个色块拼接到同一个layer并添加到self.view CALayer * layer = [CALayer layer]; layer.bounds = CGRectMake(0, 0, 100, 80); layer.position = self.view.center; [layer addSublayer:leftL]; [layer addSublayer:rightL]; [self.view.layer addSublayer:layer]; //创建一个ShapeLayer作为mask CAShapeLayer * mask = [self createShapeLayerWithPath:path]; mask.position = CGPointMake(50, 40); layer.mask = mask; //mask.strokeEnd = 1; } //依照路径创建并返回一个CAShapeLayer -(CAShapeLayer *)createShapeLayerWithPath:(UIBezierPath *)path { CAShapeLayer * layer = [CAShapeLayer layer]; layer.path = path.CGPath; layer.bounds = CGRectMake(0, 0, 100, 75); layer.position = self.view.center; layer.fillColor = [UIColor clearColor].CGColor; layer.strokeColor = [UIColor colorWithRed:33 / 255.0 green:192 / 255.0 blue:250 / 255.0 alpha:1].CGColor; layer.lineCap = @"round"; layer.lineWidth = 10; return layer; } //依照给定的颜色数组创建并返回一个CAGradientLayer -(CAGradientLayer *)createGradientLayerWithColors:(NSArray *)colors { CAGradientLayer * gradientLayer = [CAGradientLayer layer]; gradientLayer.colors = colors; gradientLayer.locations = @[@0,@0.8]; gradientLayer.startPoint = CGPointMake(0, 1); gradientLayer.endPoint = CGPointMake(0, 0); gradientLayer.bounds = CGRectMake(0, 0, 50, 80); return gradientLayer; } @end
可以改变mask的strokeEnd来实现动画
标签:property self import make nullable blog 技术 ash har
原文地址:http://www.cnblogs.com/zhouxihi/p/6295624.html