要在 iOS 上畫出圓角、漸層、陰影等自訂圖形,就繞不開 Quartz 2D。它是 Core Graphics 框架的一員,也是一套強大的二維繪圖引擎。本文從繪圖的基本步驟談起,透過實作帶你打好自訂繪圖的基礎。
Quartz 2D 是 Core Graphics 框架的一部分,UIKit 中的元件其實都是由它繪製出來的。當你引入 UIKit 框架時,系統會自動引入 Core Graphics,並在內部封裝了一些常用繪圖 API,方便開發者使用。
在 iOS 中繪圖,一般遵循以下步驟:
圖形上下文 CGContextRef 代表圖形輸出的裝置,也就是繪製的位置,包含了繪圖所需的裝置資訊。Quartz 2D 中的所有物件最終都必須畫到圖形上下文上。如此一来,繪圖時就不必關心具體裝置,統一了程式碼的撰寫方式(上下文可以是位圖、PDF、視窗、圖層或列印物件)。
在 UIKit 中,系統已預先準備好一個圖形上下文,我們可以在 UI 控件的 drawRect: 方法(在 loadView、viewDidLoad 之後執行)中,透過 UIGraphicsGetCurrentContext() 取得它。注意:在其他 UI 控件方法中無法取得這個物件。
下面自訂一個 KCView 繼承自 UIView,重寫 drawRect: 畫出兩條線段,示範完整的繪圖步驟:
#import "KCView.h"
@implementation KCView
#pragma mark 繪圖
// 繪圖只能此方法中呼叫,否則無法取得目前圖形上下文
-(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: 虛線長度間隔;count: 陣列元素個數
CGFloat lengths[2] = { 18, 9 };
CGContextSetLineDash(context, 0, lengths, 2);
// 設定陰影
CGColorRef color = [UIColor grayColor].CGColor; // UIKit 顏色轉 CGColor
CGContextSetShadowWithColor(context, CGSizeMake(2, 2), 0.8, color);
// 5. 繪製圖像到指定上下文
// 填充方式:kCGPathFill / kCGPathEOFill / kCGPathStroke / kCGPathFillStroke / kCGPathEOFillStroke
CGContextDrawPath(context, kCGPathFillStroke);
// 6. 釋放物件
CGPathRelease(path);
}
@end
由於 Quartz 2D 是跨平台的,其中的繪圖 API 無法直接使用 UIKit 的物件(例如顏色),但 UIKit 提供了 CGColor 的轉換方法,讓我們能順利銜接。
建立 KCView 並加入根視圖:
- (void)viewDidLoad {
[super viewDidLoad];
KCView *view = [[KCView alloc] initWithFrame:[UIScreen mainScreen].bounds];
view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:view];
}
掌握這套「取得上下文 → 建立路徑 → 設定狀態 → 繪製 → 釋放」的流程,你就能畫出各種自訂圖形,並進一步在這塊基礎上叠加濾鏡、漸層等進階效果。繪圖的世界很廣,這只是起點。