iOS开发中CAlayer层的属性以及自定义层的方法

2020-01-14 17:45:27于海丽


- (void)drawRect:(CGRect)rect
{
    //1.获取上下文
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    //2.绘制图形
    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 100));
    //设置属性(颜色)
    //    [[UIColor yellowColor]set];
    CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
    
    //3.渲染
    CGContextFillPath(ctx);
    //在执行渲染操作的时候,本质上它的内部相当于调用了下面的方法
    [self.layer drawInContext:ctx];
}


说明:在UIView中绘制图形,获取的上下文就是这个view对应的layer的上下文。在渲染的时候,就是把图形渲染到对应的layer上。

 

  在执行渲染操作的时候,本质上它的内部相当于执行了 [self.layer drawInContext:ctx];

 

二、第二种方式

方法描述:设置CALayer的delegate,然后让delegate实现drawLayer:inContext:方法,当CALayer需要绘图时,会调用delegate的drawLayer:inContext:方法进行绘图。

代码示例:

复制代码
//
//  YYViewController.m
//  06-自定义layer(2)
//
//  Created by apple on 14-6-21.
//  Copyright (c) 2014年 itcase. All rights reserved.

 

#import "YYViewController.h"
@interface YYViewController ()
@end


复制代码
@implementation YYViewController

 

- (void)viewDidLoad
{
    [super viewDidLoad];
    //1.创建自定义的layer
    CALayer *layer=[CALayer layer];
    //2.设置layer的属性
    layer.backgroundColor=[UIColor brownColor].CGColor;
    layer.bounds=CGRectMake(0, 0, 200, 150);
    layer.anchorPoint=CGPointZero;
    layer.position=CGPointMake(100, 100);
    layer.cornerRadius=20;
    layer.shadowColor=[UIColor blackColor].CGColor;
    layer.shadowOffset=CGSizeMake(10, 20);