// // ViewController.m // 01-CALayer创建 // // Created by mac on 16/4/18. // Copyright © 2016年 mac. All rights reserved. // /* 1. position:确定当前图层的锚点到父视图层坐标到原点的相对偏移量,在当前图层上找出锚点位置,将两者对齐 2. 绘制直线三部曲:创建可变路径(pathCreateMutable) : 添加到context(addPath) :开始绘制(drawPath) 途径阶段2:起始点确定, 属性设置(线宽和颜色) */ #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self creatCALayer]; } /** * 创建CALayer */ /* - (void)creatCALayer { CALayer *layer = [CALayer layer]; layer.bounds = CGRectMake(0, 0, 200, 200); //position和锚点决定位置,bounds决定大小 // layer.frame = CGRectMake(0, 0, 200, 200); //frame属性对于layer的约束只是大小约束,位置是由anchorPoint决定 layer.backgroundColor = [UIColor orangeColor].CGColor; [self.view.layer addSublayer:layer]; layer.position = CGPointMake(100, 300); layer.anchorPoint = CGPointZero; }*/ - (void)creatCALayer { CALayer *layer = [CALayer layer]; layer.bounds = CGRectMake(0, 0, 200, 200); //position和锚点决定位置,bounds决定大小 layer.backgroundColor = [UIColor orangeColor].CGColor; layer.anchorPoint = CGPointZero; layer.delegate = self; [self.view.layer addSublayer:layer]; [layer setNeedsDisplay]; } /** * layer的代理方法。只有设置了代理才能调用此方法 */ - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { // NSLog(@"hahahha"); CGMutablePathRef path = CGPathCreateMutable(); //1. 在图层中绘制一条线 path获取 CGPathMoveToPoint(path, NULL, 50, 50); //2. 起点 CGPathAddLineToPoint(path, NULL, 150, 150);//连线点 // [[UIColor yellowColor] setStroke]; CGContextSetRGBStrokeColor(ctx, 0, 1, 1, 1);//3. stoke线颜色 CGContextSetLineWidth(ctx, 5);//线宽 CGContextAddPath(ctx, path);//4. path添加到context CGContextDrawPath(ctx, kCGPathStroke);//5. 绘制 }