爱程序网

iOS Core Animation学习总结(2)--实现自定义图层

来源: 阅读:

一. 创建图层继承于CALayer,并在子类实现drawInContext方法

@interface CTLayer : CALayer

@end

@implementation CTLayer
-(void)drawInContext:(CGContextRef)ctx{
   //画一个圆 CGContextSetRGBFillColor(ctx,
0, 0, 1, 1); CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 100, 100)); CGContextFillPath(ctx); } @end

在viewcontroller加载视图时,

    CTLayer *layer = [CTLayer layer];
    layer.bounds = CGRectMake(0, 0, 300, 300);
    layer.anchorPoint = CGPointMake(0,0);
    [layer setNeedsDisplay];//显示图层
    [self.view.layer addSublayer:layer];

 

二. 使用代理方式创建

    CTLayer *layer = [CTLayer layer];
    layer.bounds = CGRectMake(0, 0, 300, 300);
    layer.anchorPoint = CGPointMake(0,0);
    layer.delegate = self; //指定代理,该代理可为任意类型
    [layer setNeedsDisplay];//显示layer
    [self.view.layer addSublayer:layer];

实现代理方法

#pragma mark 代理方法
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
    CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 100, 100));
    CGContextFillPath(ctx);
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助