如何自定义CALayer

CALayer的属性

宽度和高度

@property CGRect bounds;

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

@property CGPoint position;

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

@property CGPoint anchorPoint;

背景颜色(CGColorRef类型)

@property CGColorRef backgroundColor;

形变属性

@property CATransform3D transform;

边框颜色(CGColorRef类型)

@property CGColorRef borderColor;

边框宽度

@property CGFloat borderWidth;

圆角半径

@property CGColorRef borderColor;

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

@property(retain) id contents;

自定义CALayer的方式创建UIView的方式非常相似.
     CALayer *layer = [CALayer layer];
     layer.frame = CGRectMake(50, 50, 100, 100);
     layer.backgroundColor = [UIColor redColor].CGColor;
     [self.view.layer addSublayer:layer];

    给layer设置图片.
    layer.contents = (id)[UIImage imageNamed:@"阿狸头像"].CGImage;

为什么要使用CGImageRef、CGColorRef?

CALayer是定义在QuartzCore框架中的
CGImageRef、CGColorRef两种数据类型是定义在CoreGraphics框架中的

UIColor、UIImage是定义在UIKit框架中的

其次

QuartzCore框架和CoreGraphics框架是可以跨平台使用的,在iOS和Mac OS X上都能使用

但是UIKit只能在iOS中使用

为了保证可移植性,QuartzCore不能使用UIImage、UIColor,只能使用CGImageRef、CGColorRef

UIView和CALayer都能够显示东西,该怎样选择?

   对比CALayer,UIView多了一个事件处理的功能。
   也就是说,CALayer不能处理用户的触摸事件,而UIView可以
   如果显示出来的东西需要跟用户进行交互的话,用UIView;
   如果不需要跟用户进行交互,用UIView或者CALayer都可以
  CALayer的性能会高一些,因为它少了事件处理的功能,更加轻量级
- (void)viewDidLoad {
    [super viewDidLoad];

    
    CALayer *layer = [CALayer layer];
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.frame = CGRectMake(50, 50, 100, 100);
    
    [self.view.layer addSublayer:layer];
    
    layer.contents = (id)[UIImage imageNamed:@"阿狸头像"].CGImage;
  
}
如何自定义CALayer_第1张图片
阿狸头像

你可能感兴趣的:(如何自定义CALayer)