ios中自定义图层的2种方法

1:自定义图层,在图层中画图

#import <QuartzCore/QuartzCore.h>

@interface MJLayer : CALayer

@end

#import "MJLayer.h"

@implementation MJLayer

#pragma mark 在这个方法中所画的动画都会显示到MJLayer上面
- (void)drawInContext:(CGContextRef)ctx {
    // 在这里不能使用跟UIKit相关的东西
    // [[UIColor redColor] set];
    
    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
    
    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50));
    CGContextFillPath(ctx);
}

@end

==================================================================

- (void)diylayer {
MJLayer *layer = [MJLayer layer];
layer.frame = CGRectMake(50, 50, 100, 100);
layer.backgroundColor = [UIColor blueColor].CGColor;
// 只有调用这个方法才会进行第一次的绘制
[layer setNeedsDisplay];
[self.view.layer addSublayer:layer];
}



画图使用代理方式

- (void)diylayer2 {
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(50, 50, 100, 100);
    layer.backgroundColor = [UIColor blueColor].CGColor;
    // 设置代理,让代理帮图层画东西
    layer.delegate = self;
    // 只有调用这个方法才会进行第一次的绘制
    [layer setNeedsDisplay];
    [self.view.layer addSublayer:layer];
}

#pragma mark 图层的代码方法,在这里帮图层画东西
// 方法定义在QuartzCore框架中CALayer.h的@interface NSObject (CALayerDelegate)分类
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
    
    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 50, 50));
    CGContextFillPath(ctx);
}
原文地址:https://www.cnblogs.com/gcb999/p/3189277.html