iOS開發UI篇—CAlayer(自定義layer)
1 #import "YYVIEW.h" 2 3 @implementation YYVIEW 4 5 6 - (void)drawRect:(CGRect)rect 7 { 8 //1.獲取上下文 9 CGContextRef ctx=UIGraphicsGetCurrentContext(); 10 //2.繪製圖形 11 CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 100)); 12 //設定屬性(顏色) 13 // [[UIColor yellowColor]set]; 14 CGContextSetRGBFillColor(ctx, 0, 0, 1, 1); 15 16 //3.渲染 17 CGContextFillPath(ctx); 18 //在執行渲染操作的時候,本質上它的內部相當於呼叫了下面的方法 19 [self.layer drawInContext:ctx]; 20 }
說明:在UIView中繪製圖形,獲取的上下文就是這個view對應的layer的上下文。在渲染的時候,就是把圖形渲染到對應的layer上。
在執行渲染操作的時候,本質上它的內部相當於執行了 [self.layer drawInContext:ctx];
二、第二種方式
方法描述:設定CALayer的delegate,然後讓delegate實現drawLayer:inContext:方法,當CALayer需要繪圖時,會呼叫delegate的drawLayer:inContext:方法進行繪圖。
程式碼示例:
1 // 2 // YYViewController.m 3 // 06-自定義layer(2) 4 // 5 // Created by apple on 14-6-21. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 8 #import "YYViewController.h" 9 @interface YYViewController () 10 @end 11 12 @implementation YYViewController 13 14 - (void)viewDidLoad 15 { 16 [super viewDidLoad]; 17 //1.建立自定義的layer 18 CALayer *layer=[CALayer layer]; 19 //2.設定layer的屬性 20 layer.backgroundColor=[UIColor brownColor].CGColor; 21 layer.bounds=CGRectMake(0, 0, 200, 150); 22 layer.anchorPoint=CGPointZero; 23 layer.position=CGPointMake(100, 100); 24 layer.cornerRadius=20; 25 layer.shadowColor=[UIColor blackColor].CGColor; 26 layer.shadowOffset=CGSizeMake(10, 20); 27 layer.shadowOpacity=0.6; 28 29 //設定代理 30 layer.delegate=self; 31 [layer setNeedsDisplay]; 32 //3.新增layer 33 [self.view.layer addSublayer:layer]; 34 } 35 36 -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 37 { 38 //1.繪製圖形 39 //畫一個圓 40 CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 100)); 41 //設定屬性(顏色) 42 // [[UIColor yellowColor]set]; 43 CGContextSetRGBFillColor(ctx, 0, 0, 1, 1); 44 45 //2.渲染 46 CGContextFillPath(ctx); 47 } 48 @end
實現效果:
注意點:不能再將某個UIView設定為CALayer的delegate,因為UIView物件已經是它內部根層的delegate,再次設定為其他層的delegate就會出問題。
在設定代理的時候,它並不要求我們遵守協議,說明這個方法是nsobject中的,就不需要再額外的顯示遵守協議了。
提示:以後如果要設定某個類的代理,但是這個代理沒要求我們遵守什麼特定的協議,那麼可以認為這個協議方法是NSObject裡邊的。
三、補充說明
(1)無論採取哪種方法來自定義層,都必須呼叫CALayer的setNeedsDisplay方法才能正常繪圖。
(2)詳細現實過程:
當UIView需要顯示時,它內部的層會準備好一個CGContextRef(圖形上下文),然後呼叫delegate(這裡就是UIView)的drawLayer:inContext:方法,並且傳入已經準備好的CGContextRef物件。而UIView在drawLayer:inContext:方法中又會呼叫自己的drawRect:方法。平時在drawRect:中通過UIGraphicsGetCurrentContext()獲取的就是由層傳入的CGContextRef物件,在drawRect:中完成的所有繪圖都會填入層的CGContextRef中,然後被拷貝至螢幕。