CALayer4-自定義層


自定義層,其實就是在層上繪圖,一共有2種方法,下面詳細介紹一下。

一、自定義層的方法1

方法描述:創建一個CALayer的子類,然后覆蓋drawInContext:方法,使用Quartz2D API進行繪圖

1.創建一個CALayer的子類

 

2.在.m文件中覆蓋drawInContext:方法,在里面繪圖

 1 @implementation MJLayer
 2 
 3 #pragma mark 繪制一個實心三角形
 4 - (void)drawInContext:(CGContextRef)ctx {
 5     // 設置為藍色
 6     CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
 7 
 8     
 9     // 設置起點
10     CGContextMoveToPoint(ctx, 50, 0);
11     // 從(50, 0)連線到(0, 100)
12     CGContextAddLineToPoint(ctx, 0, 100);
13     // 從(0, 100)連線到(100, 100)
14     CGContextAddLineToPoint(ctx, 100, 100);
15     // 合並路徑,連接起點和終點
16     CGContextClosePath(ctx);
17     
18     // 繪制路徑
19     CGContextFillPath(ctx);
20 }
21 
22 @end

 

3.在控制器中添加圖層到屏幕上

1 MJLayer *layer = [MJLayer layer];
2 // 設置層的寬高
3 layer.bounds = CGRectMake(0, 0, 100, 100);
4 // 設置層的位置
5 layer.position = CGPointMake(100, 100);
6 // 開始繪制圖層
7 [layer setNeedsDisplay];
8 [self.view.layer addSublayer:layer];

注意第7行,需要調用setNeedsDisplay這個方法,才會觸發drawInContext:方法的調用,然后進行繪圖

 

二、自定義層的方法2

方法描述:設置CALayer的delegate,然后讓delegate實現drawLayer:inContext:方法,當CALayer需要繪圖時,會調用delegate的drawLayer:inContext:方法進行繪圖。

* 這里要注意的是:不能再將某個UIView設置為CALayer的delegate,因為UIView對象已經是它內部根層的delegate,再次設置為其他層的delegate就會出問題。UIView和它內部CALayer的默認關系圖:

1.創建新的層,設置delegate,然后添加到控制器的view的layer中

 1 CALayer *layer = [CALayer layer];
 2 // 設置delegate
 3 layer.delegate = self;
 4 // 設置層的寬高
 5 layer.bounds = CGRectMake(0, 0, 100, 100);
 6 // 設置層的位置
 7 layer.position = CGPointMake(100, 100);
 8 // 開始繪制圖層
 9 [layer setNeedsDisplay];
10 [self.view.layer addSublayer:layer];

* 在第3行設置了CALayer的delegate,這里的self是指控制器

* 注意第9行,需要調用setNeedsDisplay這個方法,才會通知delegate進行繪圖

 

2.讓CALayer的delegate(前面設置的是控制器)實現drawLayer:inContext:方法

 1 #pragma mark 畫一個矩形框
 2 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
 3     // 設置藍色
 4     CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1);
 5     // 設置邊框寬度
 6     CGContextSetLineWidth(ctx, 10);
 7     
 8     // 添加一個跟層一樣大的矩形到路徑中
 9     CGContextAddRect(ctx, layer.bounds);
10     
11     // 繪制路徑
12     CGContextStrokePath(ctx);
13 } 

 

 三、其他

1.總結

無論采取哪種方法來自定義層,都必須調用CALayer的setNeedsDisplay方法才能正常繪圖。

 

2.UIView的詳細顯示過程

* 當UIView需要顯示時,它內部的層會准備好一個CGContextRef(圖形上下文),然后調用delegate(這里就是UIView)的drawLayer:inContext:方法,並且傳入已經准備好的CGContextRef對象。而UIView在drawLayer:inContext:方法中又會調用自己的drawRect:方法

* 平時在drawRect:中通過UIGraphicsGetCurrentContext()獲取的就是由層傳入的CGContextRef對象,在drawRect:中完成的所有繪圖都會填入層的CGContextRef中,然后被拷貝至屏幕


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM