CALayer可以完成很多任务
CALayer与UIView
CALayer在系统架构中的位置
适用于iOS与Mac OS X
适用于iOS与Mac OS X
只适用于iOS
frame属性
border属性
cornerRadius(CGFloat),圆角属性,若控件的宽高相等,且圆角属性为宽/高的一半,则为圆形,原理如图
borderWidth(CGFloat),边框的宽度
,与contentInsets的效果相似
appearance属性
content属性
backgroundColor、content与border的层次关系,如图
示例
若position为(100, 100),anchorPoint为(0, 0 ),如图
若position为(100, 100),anchorPoint为(0.5, 0.5),如图
创建一个CALayer对象imageLayer,并添加到控制器View的layer上
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
设置背景图片
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//设置背景颜色imageLayer.backgroundColor = [UIColor orangeColor].CGColor;//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
显示效果如图
设置imageLayer的内容为一张图片
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//在图层上添加一张图片imageLayer.contents = (id)[UIImage imageNamed:@"Ali"].CGImage;//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
显示效果如图
设置圆角属性
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//设置圆角属性imageLayer.cornerRadius = 20;imageLayer.masksToBounds = YES; //该属性在iOS9中不用设置//在图层上添加一张图片imageLayer.contents = (id)[UIImage imageNamed:@"Ali"].CGImage;//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
显示效果如图
设置边框属性
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//设置圆角属性imageLayer.cornerRadius = 20;imageLayer.masksToBounds = YES;//设置border属性imageLayer.borderWidth = 2;imageLayer.borderColor = [UIColor purpleColor].CGColor;//在图层上添加一张图片imageLayer.contents = (id)[UIImage imageNamed:@"Ali"].CGImage;//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
显示效果如图
方法一:创建CALayer对象,并设置其代理
创建CALayer对象
//创建图层CALayer *imageLayer = [[CALayer alloc] init];//设置代理imageLayer.delegate = self;//设置图层的位置和尺寸imageLayer.bounds = CGRectMake(0, 0, 100, 100);imageLayer.position = CGPointMake(100, 200);//重绘[imageLayer setNeedsDisplay];//将图层添加到控制器view的layer上[self.view.layer addSublayer:imageLayer];
实现代理方法,在该方法中绘制图层的内容
- (void)drawLayer:(nonnull CALayer *)layer inContext:(nonnull CGContextRef)ctx{ //通过绘图方法绘制内容}
方法二:自定义CALayer类的子类
自定义CALayer的子类ImageLayer
//重写该方法,绘制图层的内容- (void)drawInContext:(nonnull CGContextRef)ctx{ //通过绘图方法绘制内容}
创建ImageLayer的实例
ImageLayer *imageLayer = [[ImageLayer alloc] init];[self.view.layer addSublayer:imageLayer];
新闻热点
疑难解答