1、CAShapeLayer
CGPath能表示的形状,CAShapeLayer都可以绘制出来。换句话说CGPath可以限制CAShapeLayer的形状。CAShapeLayer有一个属性Path,将路径赋值给这个属性即可。下面是一些应用场景。
1️⃣作为遮罩:CAShapeLayer可以作为其他图层的遮罩使用,用于限制其他图层的形状,通过图层的mask属性赋值。下面是绘制一个圆形的图片,通常我们通过设置imageView.layer的圆角半径来让imageView变成圆形,现在可以直接使用CAShapeLayer生成一个圆形遮罩覆盖在imageView上
//创建imageView
UIImageView *imagev = [[UIImageView alloc] init];
imagev.frame = CGRectMake(100, 100, 100, 100); //边长100的正方形
[self.view addSubview:imagev];
CAShapeLayer *shaplayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath]; //创建路径
[path addArcWithCenter:CGPointMake(50, 50) radius:50 startAngle:0 endAngle:M_PI*2 clockwise:YES]; //圆形路径 注意这里的center是以imageView为坐标系的
shaplayer.path = path.CGPath; //要转成CGPath
imagev.layer.mask = shaplayer; //限制imageView的外形
注意:
- 作为遮罩时不用设置颜色属性,只需设置path属性。
- 作为遮罩时才会限制父layer的形状
- 作为子layer时不会限制父layer的形状
2️⃣动画效果:通过不断的改变CAShapeLayer的path从而达到动画的效果,可以做出核心动画难以实现的效果,比如粘性动画、单边的弹性下拉效果、qq的粘性按钮效果、正弦波浪线等等,相当丰富,我这里提供几个链接
3️⃣注意两个属性strokeStart和strokeEnd,这两个属性用于对绘制的Path进行区域限制,值为0-1之间,并且这两个属性可做动画,例子如下。
- (void)viewDidLoad {
[super viewDidLoad];
CAShapeLayer *layer = [CAShapeLayer layer];
layer.strokeColor = kRedColor.CGColor;
layer.fillColor = kClearColor.CGColor;
layer.lineWidth = 2; //通过调整线宽可以做成饼状图
UIBezierPath *path = [UIBezierPath bezierPath];
//值得一提的是这里圆的起点是-π
[path addArcWithCenter:CGPointMake(150, 150) radius:100 startAngle:-M_PI endAngle:M_PI clockwise:YES];
layer.path = path.CGPath;
layer.strokeEnd = 0.0;
self.layer = layer;
[self.view.layer addSublayer:layer];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"strokeEnd";
anim.fromValue = @0.0;
anim.toValue = @1.0;
anim.duration = 2;
anim.repeatCount = 100;
[self.layer addAnimation:anim forKey:nil];
}
4️⃣虚线效果
虚线效果只需设置lineDashPattern 属性。self.shapLayer.lineDashPattern = @[@(4),@(4)];
数组中第一个4表示先画4个点的实线,第二4表示接着间隔4个点不画线
5️⃣二维码扫描框
二维码的扫描框通常是中间矩形为透明,其余边框为带透明度的黑色
//包裹self.view的路径
UIBezierPath *overlayPath = [UIBezierPath bezierPathWithRect:self.view.bounds];
//中间透明边框的路径
UIBezierPath *transparentPath = [UIBezierPath bezierPathWithRect:CGRectMake(100, 150, 200, 200)];
//合并为一个路径
[overlayPath appendPath:transparentPath];
CAShapeLayer *layer = [CAShapeLayer layer];
layer.path = overlayPath.CGPath;
layer.fillRule = kCAFillRuleEvenOdd; //奇偶填充规则
layer.fillColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
[self.view.layer addSublayer:layer];
2、CATextLayer
CATextLayer的绘制功能要比UILabel强大很多,并且速度要快不少。
简单使用
CATextLayer *textLayer = [CATextLayer layer];
textLayer.string = @"123abcABC123abcABC123abcABC123abcABC123abcABC123abcABC123a3abcABC123abcABC123abcABC123a3abcABC123abcABC123abcABC123abcABC123abcABC呵呵呵";
textLayer.font = CGFontCreateWithFontName((__bridge CFStringRef)(@"Georgia"));
textLayer.fontSize = 12;
textLayer.backgroundColor = kYellowColor.CGColor;
textLayer.foregroundColor = kRedColor.CGColor; //文字颜色,普通字符串时可以使用该属性
textLayer.wrapped = YES; //为yes时自动换行
textLayer.truncationMode = @"start"; //字符串过长时的省略位置,注意是最后一行的哪个位置
// textLayer.alignmentMode = kCAAlignmentCenter; //对齐方式
// textLayer.allowsFontSubpixelQuantization = NO;
textLayer.frame = CGRectMake(0, 0, 100, 100);
// textLayer.position = self.view.center; //图层的中心点位于父层的位置
textLayer.contentsScale = [UIScreen mainScreen].scale; //按当前的屏幕分辨率显示 否则字体会模糊
[self.view.layer addSublayer:textLayer];
3、CATransformLayer
CATransformLayer是一个容器layer,backgroundColor等外观显示属性对他是无效的,CATransformLayer只是一个容器,只负责容纳其他layer并显示其他layer。CATransformLayer通常用于构造复杂的3D事物,他不是一个平面化的图层,能够构造多层次的3D结构。这里就创建一个简单的立方体,代码如下。
@interface ViewController ()
@property (nonatomic,strong) NSMutableArray<CALayer *> *layerArray;
@property (nonatomic,strong) NSMutableArray *transArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建图层
CATransformLayer *cublayer = [CATransformLayer layer];
// layer.borderColor = kBlackColor.CGColor; //这些属性设置都是无效的
// layer.borderWidth = 1;
// layer. backgroundColor = [UIColor redColor].CGColor;
cublayer.bounds = CGRectMake(0, 0, 200, 200);
cublayer.position = self.view.center;
[self.view.layer addSublayer:cublayer];
//对容器图层做动画
CATransform3D transA = CATransform3DMakeRotation(M_PI, 1, 1, 0);
CATransform3D transB = CATransform3DMakeRotation(M_PI*2, 1, 1, 0);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
animation.duration = 4;
animation.autoreverses = YES;
animation.repeatCount = 100;
animation.fromValue = [NSValue valueWithCATransform3D:transA];
animation.toValue = [NSValue valueWithCATransform3D:transB];
[cublayer addAnimation:animation forKey:nil];
//创建立方体的6个面
self.layerArray = [NSMutableArray array];
for (NSInteger i = 0; i<6; i++) {
CALayer *sublayer = [CALayer layer];
sublayer.bounds = CGRectMake(0, 0, 100, 100);
sublayer.position = CGPointMake(100, 100);
sublayer.backgroundColor = kRandomColorAndAlpha(0.3).CGColor;
sublayer.speed = 0.1;
[self.layerArray addObject:sublayer];
[cublayer addSublayer:sublayer];
}
//为六个面的图层创建3D变换,使之组成立方体
CATransform3D ct1 = CATransform3DMakeTranslation(0, 0, 50);
CATransform3D ct2 = CATransform3DMakeTranslation(0, 0, -50);
CATransform3D ct3 = CATransform3DMakeTranslation(-50, 0, 0);
ct3 = CATransform3DRotate(ct3, M_PI_2, 0, 1, 0);
CATransform3D ct4 = CATransform3DMakeTranslation(50, 0, 0);
ct4 = CATransform3DRotate(ct4, M_PI_2, 0, 1, 0);
CATransform3D ct5 = CATransform3DMakeTranslation(0, -50, 0);
ct5 = CATransform3DRotate(ct5, M_PI_2, 1, 0, 0);
CATransform3D ct6 = CATransform3DMakeTranslation(0, 50, 0);
ct6 = CATransform3DRotate(ct6, M_PI_2, 1, 0, 0);
//存入数组待用
self.transArray = [NSMutableArray arrayWithArray:@[[NSValue valueWithCATransform3D:ct1],
[NSValue valueWithCATransform3D:ct2],
[NSValue valueWithCATransform3D:ct3],
[NSValue valueWithCATransform3D:ct4],
[NSValue valueWithCATransform3D:ct5],
[NSValue valueWithCATransform3D:ct6]]];
}
//一开始六个面叠在一起,点击屏幕后,立方体的六个面慢慢归位
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
for (NSInteger i = 0; i<6; i++) {
NSValue *value = self.transArray[I];
CATransform3D ct = [value CATransform3DValue];
CALayer *layer = self.layerArray[I];
[UIView animateWithDuration:1.0 animations:^{
layer.transform = ct;
}];
}
}
4、CAGradientLayer
CAGradientLayer是用来生成两种或更多颜色平滑渐变的图层,总而言之就是渐变图层。
这里需要注意一个属性locations ,locations 表示的是渐变区间,数组中的数字必须是递增的。比如下面这个例子layer.locations = @[@0.5,@0.8]; 渐变区间是0.5-0.8,也就是说0.0-0.5是纯红色,0.5-0.8是红色渐变到绿色,0.8-1.0是纯绿色。不设置这个属性就是整个区间0.0-1.0均匀渐变。
1️⃣基础渐变,双色渐变
由红色渐变到绿色
CAGradientLayer *layer = [CAGradientLayer layer];
layer.frame = self.view.bounds;
//颜色梯度数组,需要渐变的颜色
layer.colors = @[(__bridge id)kRedColor.CGColor,(__bridge id)kGreenColor.CGColor];
//渐变区间,
layer.locations = @[@0.5,@0.8];
[self.view.layer addSublayer:layer];
2️⃣单色渐变
红色的渐变,单色渐变其实就是双色渐变,这里要说明另外两个属性startPoint和endPoint,这两个属性是一起使用的,用于确定渐变方向。
CAGradientLayer *layer = [CAGradientLayer layer];
layer.frame = self.view.bounds;
layer.colors = @[(__bridge id)kRedColor.CGColor,(__bridge id)kWhiteColor.CGColor];
layer.startPoint = CGPointMake(0, 0);
layer.endPoint = CGPointMake(0.5, 1);
[self.view.layer addSublayer:layer];
3️⃣多色渐变 彩虹🌈
4️⃣文字的色彩渐变
- (void)viewDidLoad {
[super viewDidLoad];
//1、创建label
UILabel *label = [[UILabel alloc] init];
label.text = @"呵呵🙃";
label.font = [UIFont systemFontOfSize:30];
[self.view addSubview:label];
//2、创建渐变图层
CAGradientLayer *layer = [CAGradientLayer layer];
layer.frame = CGRectMake(0, 0, 100, 50);
layer.colors = @[(__bridge id)kRedColor.CGColor,(__bridge id)kGreenColor.CGColor];
layer.locations = @[@0.5,@0.8];
[self.view.layer addSublayer:layer];
//3、设置遮罩
layer.mask = label.layer;
label.frame = layer.bounds;
}
5️⃣使用Core Graphics相关方法实现渐变
iOS Core Graphics中有两个方法用于绘制渐变颜色,CGContextDrawLinearGradient可以用于生成线性渐变,CGContextDrawRadialGradient用于生成圆半径方向颜色渐变。函数可以自定义path,无论是什么形状都可以,原理都是用来做Clip,所以需要在CGContextClip函数前调用CGContextAddPath函数把CGPathRef加入到Context中。
另外一个需要注意的地方是渐变的方向,方向是由两个点控制的,点的单位就是坐标。因此需要正确从CGPathRef中找到正确的点,方法当然有很多种看具体实现,本例中,我就是简单得通过调用CGPathGetBoundingBox函数,返回CGPathRef的矩形区域,然后根据这个矩形取两个点。
线性渐变
- (void)drawLinearGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
//具体方向可根据需求修改
CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMidY(pathRect));
CGPoint endPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMidY(pathRect));
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//创建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//绘制Path
CGRect rect = CGRectMake(0, 100, 300, 200);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
CGPathCloseSubpath(path);
//绘制渐变
[self drawLinearGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
//注意释放CGMutablePathRef
CGPathRelease(path);
//从Context中获取图像,并显示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}
圆半径方向渐变
- (void)drawRadialGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
CGPoint center = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));
CGFloat radius = MAX(pathRect.size.width / 2.0, pathRect.size.height / 2.0) * sqrt(2);
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextEOClip(context);
CGContextDrawRadialGradient(context, gradient, center, 0, center, radius, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//创建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//绘制Path
CGRect rect = CGRectMake(0, 100, 300, 200);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMinY(rect));
CGPathCloseSubpath(path);
//绘制渐变
[self drawRadialGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
//注意释放CGMutablePathRef
CGPathRelease(path);
//从Context中获取图像,并显示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}
5、CAReplicatorLayer
CAReplicatorLayer就是复制图层。CAReplicatorLayer又是一个容器图层,他可以将他的子图层复制指定的次数,复制出来的这些图层都拥有相同的图层属性和动画属性,通过下面的例子来介绍一些重要的属性
1️⃣辐射动画
属性instanceCount表示拷贝图层的次数,默认为1 。 举个栗子instanceCount = 6 表示总共有6个子图层,其中5个是拷贝出来的。
属性instanceDelay表示拷贝延时,拷贝一个图层后延时多少秒拷贝下一个图层
这里为了使动画连续,我让动画的duration = 0.6 * 6 = 3.6
//创建复制图层容器
CAReplicatorLayer *replicator = [CAReplicatorLayer layer];
replicator.frame = self.view.bounds;
[self.view.layer addSublayer:replicator];
replicator.instanceCount = 6;
replicator.instanceDelay = 0.6;
//放大动画
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"transform.scale";
anim.fromValue = @1;
anim.toValue = @20;
anim.duration = 3.6;
//透明度动画
CABasicAnimation *anim2 = [CABasicAnimation animation];
anim2.keyPath = @"opacity";
anim2.toValue = @0.0;
anim2.fromValue = @1.0;
anim2.duration = 3.6;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = @[anim,anim2];
group.duration = 3.6;
group.repeatCount = 100;
//创建子图层
CALayer *layer = [CALayer layer];
[layer addAnimation:group forKey:nil];
layer.bounds = CGRectMake(0, 0, 10, 10);
layer.position = self.view.center;
layer.cornerRadius = 5;
layer.backgroundColor = kRedColor.CGColor;
[replicator addSublayer:layer];
更改一下属性replicator.instanceCount = 3; 动画就不连续了
2️⃣加载动画
属性instanceTransform 表示复制图层在被创建时产生的和上一个复制图层的位移
CAReplicatorLayer *replicator = [CAReplicatorLayer layer];
replicator.frame = self.view.bounds;
[self.view.layer addSublayer:replicator];
replicator.instanceCount = 6;
replicator.instanceDelay = 0.2;
//位移属性
CATransform3D trans = CATransform3DMakeTranslation(25, 0, 0); //圆点依次向右移动25
replicator.instanceTransform = trans;
//透明度动画
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"opacity";
anim.values = @[@1.0,@0.0,@1.0];
anim.duration = 1.2;
anim.repeatCount = 100;
CALayer *layer = [CALayer layer];
[layer addAnimation:anim forKey:nil];
layer.bounds = CGRectMake(0, 0, 20, 20);
layer.position = self.view.center;
layer.cornerRadius = 10;
layer.backgroundColor = kRedColor.CGColor;
[replicator addSublayer:layer];
其他的一些属性
instanceColor : 设置多个复制图层的颜色,默认位白色
//RGB偏移量
instanceRedOffset: 设置每个复制图层相对上一个复制图层的红色偏移量
instanceGreenOffset: 设置每个复制图层相对上一个复制图层的绿色偏移量
instanceBlueOffset: 设置每个复制图层相对上一个复制图层的蓝色偏移量
instanceAlphaOffset: 设置每个复制图层相对上一个复制图层的透明度偏移量
以下就是设置instanceAlphaOffset = -0.1的效果,其他几个属性用法类似
CAReplicatorLayer *replicator = [CAReplicatorLayer layer];
replicator.frame = self.view.bounds;
[self.view.layer addSublayer:replicator];
replicator.instanceCount = 6;
replicator.instanceAlphaOffset = -0.1; // 透明度递减,每个图层都比上一个复制图层的透明度小0.1
CATransform3D trans = CATransform3DMakeTranslation(25, 0, 0);
replicator.instanceTransform = trans;
CALayer *layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 20, 20);
layer.position = self.view.center;
layer.cornerRadius = 10;
layer.backgroundColor = kRedColor.CGColor;
[replicator addSublayer:layer];
3️⃣着重介绍一下instanceTransform属性,还是通过例子吧
CAReplicatorLayer *replicator = [CAReplicatorLayer layer];
replicator.frame = self.view.bounds;
[self.view.layer addSublayer:replicator];
replicator.instanceCount = 2;
CATransform3D trans = CATransform3DMakeTranslation(0, -50, 0); //y的负方向平移50 也就是方块的上方
trans = CATransform3DRotate(trans, M_PI_4, 0, 0, 1); //然后旋转45度
replicator.instanceTransform = trans;
CALayer *layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 30, 30);
layer.position = self.view.center;
layer.backgroundColor = kRedColor.CGColor;
[replicator addSublayer:layer];
我们来看看instanceTransform是怎么运作的,先设置replicator.instanceCount = 2; 效果如下,很明显上面那个小方块向上平移了50个点然后旋转了45度。
设置replicator.instanceCount = 3; 效果如下,由于方块2旋转了45度,所以方块2的上方(黑色边表示上方)也是旋转之后的上方,方块3就是沿着方块2的上方平移50点然后再旋转45度。
设置replicator.instanceCount = 4; 经过上面的推断,下面的效果应该能自己想出来了。
这里要特别注意CATransform3DRotate旋转变换,该方块旋转之后自己的坐标系也发生了同样角度的旋转(感觉是每个方块都有自己的坐标系),在旋转之后再要进行平移操作,那也是按照旋转之后的坐标系进行平移。 (上面的推断纯属个人判断,如有错误还望指正!)
CATransform3D trans = CATransform3DMakeTranslation(0, -50, 0);
trans = CATransform3DRotate(trans, M_PI_4, 0, 0, 1);
trans = CATransform3DTranslate(trans, 21, 0, 0); //按照上面旋转之后的坐标系进行平移(当前坐标系的右方向平移21)
6、CAScrollLayer
- (void)viewDidLoad {
[super viewDidLoad];
CALayer *layer = [CALayer layer];
layer.contents = (id)kImage(@"111").CGImage;
layer.frame = CGRectMake(0, 0, 375, 667);
self.scrollLayer = [CAScrollLayer layer];
self.scrollLayer.frame = CGRectMake(60, 60, 200, 200);
[self.scrollLayer addSublayer:layer];
self.scrollLayer.scrollMode = kCAScrollBoth;
[self.view.layer addSublayer:self.scrollLayer];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureChanged:)];
[self.view addGestureRecognizer:pan];
}
-(void)gestureChanged:(UIPanGestureRecognizer *)gesture
{
CGPoint translation = [gesture translationInView:self.view];
CGPoint origin = self.scrollLayer.bounds.origin;
origin = CGPointMake(origin.x-translation.x, origin.y-translation.y);
[self.scrollLayer scrollToPoint:origin];
[gesture setTranslation:CGPointZero inView:self.view];
}
7、CATiledLayer
8、CAEmitterLayer
下面这两篇文章写的不错,我就没必要再写了
https://www.jianshu.com/p/197c2257f597
https://www.cnblogs.com/densefog/p/5424155.html
https://www.kancloud.cn/manual/ios/97766
注意点:birthRate、velocity和lifetime属性是对CAEmitterCell设置的,对CAEmitterLayer设置无效