標籤:
想要自訂圖層,只需要構建一個類繼承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];
【iOS開發-圖層】自訂圖層的兩種方式