【iOS開發-圖層】自定義圖層的兩種方式

想要自定義圖層,只需要構建一個類繼承CALayer方法

這裏寫圖片描述

如果讓自定義圖層初始化上面就有畫好的圖形,有兩種辦法

重寫drawInContext方法

自定義的圖層下面的方法,然後必須自定義的圖層對象顯示調用
[layer setNeedsDisplay]然後纔會調用這個方法;

自定圖層文件

- (void)drawInContext:(CGContextRef)ctx {
    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);//設置紅色

    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50));//畫圓

    CGContextFillPath(ctx);
}

控制器文件

 TestLayer *layer = [TestLayer layer];
    layer.bounds = CGRectMake(0, 0, 100, 100);
    layer.position = CGPointMake(100, 100);
    layer.anchorPoint = CGPointMake(0, 0);
    layer.backgroundColor = [UIColor blueColor].CGColor;
    layer.cornerRadius = 10;
    [layer setNeedsDisplay];//必須要顯示調用這個方法,纔會調用上面的那個方法
    [self.view.layer addSublayer:layer];

使用代理

首先代理控制器不需要遵循協議,因爲這個協議是一個分類,所有的NSObject都實現了

控制器實現代理的方法

#pragma marks -實現代理的方法
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);

    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50));

    CGContextFillPath(ctx);
}

調用

TestLayer *layer = [TestLayer layer];
layer.bounds = CGRectMake(0, 0, 100, 100);
layer.position = CGPointMake(100, 100);
layer.anchorPoint = CGPointMake(0, 0);
layer.backgroundColor = [UIColor blueColor].CGColor;
layer.cornerRadius = 10;
layer.delegate = self;
[layer setNeedsDisplay];//必須顯示調用,不然也不會調用代理的方法
[self.view.layer addSublayer:layer];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章