要在 iOS 上畫出三角形、圓角、漸層或陰影,最終都會回到同一個引擎:Quartz 2D。它是 Core Graphics 框架的一部分,也是 UIKit 所有元件背後的作畫者。
Quartz 2D 是一個強大的二維繪圖引擎。我們日常使用的 UIKit 元件,其實都是由 Core Graphics 一筆一筆畫出來的;當你引入 UIKit 時,系統會自動帶入 Core Graphics,並在 UIKit 內部把常用 API 再包一層,讓開發者用起來更直覺。
這也解釋了為什麼自訂 View 的繪圖邏輯,和系統元件的呈現方式其實是同一套東西。
CGContextRef 代表「畫到哪裡去」,也就是繪圖的輸出裝置,同時保存了線寬、顏色、陰影等設備相關資訊。Quartz 2D 中的所有物件最後都必須畫到某個上下文上。
這個抽象化的設計有個好處:你不必在意目標是螢幕還是印表機,程式碼寫法完全一致。常見的上下文來源包括 Bitmap、PDF、Window、Layer 與 Printer。
UIKit 已經為每個 View 準備好一個上下文,但只有在 drawRect: 方法中可以取得(這個方法在 loadView、viewDidLoad 之後執行)。其他 UI 方法呼叫 UIGraphicsGetCurrentContext() 會拿到 nil。
實作方式是自己寫一個繼承 UIView 的子類,例如 KCView,並覆寫 drawRect::
#import "KCView.h"
@implementation KCView
// 繪圖只能在此方法中進行,否則取不到當前上下文
- (void)drawRect:(CGRect)rect {
// 1. 取得圖形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 2. 建立路徑
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, 20, 50); // 設定起點
CGPathAddLineToPoint(path, nil, 20, 100); // 畫出第一段直線
CGPathAddLineToPoint(path, nil, 300, 100); // 從上一點繼續畫
// 3. 把路徑加入上下文
CGContextAddPath(context, path);
// 4. 設定上下文狀態
CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1); // 筆觸顏色
CGContextSetRGBFillColor(context, 0, 1.0, 0, 1); // 填充顏色
CGContextSetLineWidth(context, 2.0); // 線寬
CGContextSetLineCap(context, kCGLineCapRound); // 端點樣式
CGContextSetLineJoin(context, kCGLineJoinRound); // 轉角樣式
// 虛線:phase 為起始偏移,lengths 描述「實線長度、間隔」的循環
CGFloat lengths[2] = { 18, 9 };
CGContextSetLineDash(context, 0, lengths, 2);
// 陰影:offset 偏移量、blur 模糊度、color 陰影顏色
// 注意 Quartz 2D 跨平台,不能直接吃 UIColor,需轉成 CGColor
CGColorRef color = [UIColor grayColor].CGColor;
CGContextSetShadowWithColor(context, CGSizeMake(2, 2), 0.8, color);
// 5. 繪製到上下文,參數為填充模式
CGContextDrawPath(context, kCGPathFillStroke);
// 6. 釋放路徑
CGPathRelease(path);
}
@end
kCGPathFill:只有填充(非零環繞數規則),不畫邊框。kCGPathEOFill:奇偶規則填充,路徑交疊處奇數填、偶數不填。kCGPathStroke:只畫邊框。kCGPathFillStroke:邊框與填充都畫。kCGPathEOFillStroke:奇偶填充並畫邊框。- (void)viewDidLoad {
[super viewDidLoad];
KCView *view = [[KCView alloc] initWithFrame:[UIScreen mainScreen].bounds];
view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:view];
}
用 CGMutablePathRef 建立的路徑必須手動 CGPathRelease,這是MRC 時代留下的習慣;若在 ARC 專案中使用 Core Graphics 物件, likewise 仍要自行管理,因為 ARC 不接管 Core Foundation 家族。
另外,drawRect: 每次重繪都會重新執行,因此不要在裡面做重運算或 I/O。真正需要頻繁更新時,改用 CALayer 或 Core Animation 會更有效率。