CALayer的可动画属性和使用CALayer的代理来绘图

一、CALayer的可动画属性
//1.取出触到屏幕上的点
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
//2.将这个点设置为position
_layer.position = location;
//3.随机生成颜色
NSInteger i = arc4random_uniform(_colors.count);
_layer.backgroundColor = [_colors[i] CGColor];
//4.透明度
CGFloat alpha = arc4random_uniform(5) / 10.0 + 0.6;//随机生成0-0.6的透明度
_layer.opacity = alpha;
//5.旋转角度
CGFloat angle = arc4random_uniform(180) / M_PI * 180;//随机生成0-180度
_layer.transform = CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0);
//6.随机圆角属性
NSInteger r = arc4random_uniform(50) + 20; //随机生成20-70的半径
_layer.cornerRadius = r;
二、使用CALayer的代理来绘图---->必须自定义图层,并且设置代理,调用setNeedDisplay方法
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
NSLog(@"drawLayer");
//1、设置绘图区域
CGRect rect = CGRectMake(50, 50, 100, 100);
//2、添加到上下文
CGContextAddRect(ctx, rect);
//3、设置上下文属性
CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
//4、开始画
CGContextDrawPath(ctx, kCGPathStroke);
}

原文地址:https://www.cnblogs.com/yinqiang/p/3486796.html