ios-CALayer图层基本概念和用法

 

1、CALayer简单的概述

 在iOS中,你能看得见摸得着的东西基本上都是UIView,比如一个按钮、一个文本标签、一个文本输入框、一个图标等等,这些都是UIView

 

其实UIView之所以能显示在屏幕上,完全是因为它内部的一个图层

在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层

 

 @property(nonatomic,readonly,retain) CALayer *layer; 

 

当UIView需要显示到屏幕上时,会调用drawRect:方法进行绘图,并且会将所有内容绘制在自己的图层上,绘图完毕后,系统会将图层拷贝到屏幕上,于是就完成了UIView的显示

 

换句话说,UIView本身不具备显示的功能,是它内部的层才有显示功能


2、UIView与CALayer最主要的区别是什么呢

UIView与CALayer两者都可以用来显示东西,不同之处在于UIView还包含了事件点击,可以进行用户交互,而CALayer只是单纯的用于显示。

 

3、CALayer的常用属性

宽度和高度

@property CGRect bounds;

 

位置(默认指中点,具体由anchorPoint决定)

 @property CGPoint position;

 

锚点(x,y的范围都是0-1),决定了position的含义

 @property CGPoint anchorPoint;

 

背景颜色(CGColorRef类型)

@property CGColorRef backgroundColor;

 

形变属性,可以实现3D的移动缩放旋转效果, UIView的transform属性是2D的

@property CATransform3D transform;

 

边框颜色(CGColorRef类型)

 

@property CGColorRef borderColor;

 

边框宽度

 

@property CGFloat borderWidth;

 

圆角半径

 

@property CGColorRef borderColor;

 

 

内容(比如设置为图片CGImageRef)

 

@property(retain) id contents;

 

 

4、两个重要的属性position和anchorPoint

 

position用来设置CALayer在父层中的位置,以父层的左上角为原点(0, 0)

 

anchorPoint,称为“定位点”、“锚点”,决定着CALayer身上的哪个点会在position属性所指的位置,以自己的左上角为原点(0, 0),它的x、y取值范围都是0~1,默认值为(0.5, 0.5),如下图:

 

 

 

 

 

 

 

 

4、自己创建图层

 

 1  //自定义图层
 2     CALayer *layer = [CALayer layer];
 3     //设置背景颜色
 4     layer.backgroundColor = [UIColor redColor].CGColor;
 5     //设置圆角
 6     layer.cornerRadius = 10.0f;
 7     //设置边框
 8     layer.borderWidth = 10;
 9     //设置边框颜色
10     layer.borderColor = [UIColor yellowColor].CGColor;
11     //设置尺寸大小
12     layer.bounds = CGRectMake(0, 0, 200, 200);
13     //设置图层位置
14     layer.position = CGPointMake(100, 100);
15     //设置锚点,设置自己身上的哪个点处于position所指的位置
16     layer.anchorPoint = CGPointMake(0, 0);
17     //设置图层显示内容,会把内容绘制到图层上显示出来,如图片
18     layer.contents = (id)[UIImage imageNamed:@"me"].CGImage;
19     //把图层天加到控制器view的图层上
20     [self.view.layer addSublayer:layer];
21 }

 

posted @ 2015-11-08 16:09  原谅我一生放纵不羁  阅读(1077)  评论(0编辑  收藏  举报