iOS 圖形繪製並非單一 API,而是由四大引擎分層協作。理解它們的分工、觸發機制與性能特性,是構建高性能流暢界面的前提。
| 引擎 | 層級 | 語言 | 核心能力 | 典型場景 |
|---|---|---|---|---|
| OpenGL ES | 最底層 | C | GPU 直接編程、2D/3D 渲染管線、著色器 | 遊戲、AR/VR、高性能圖表、濾鏡 |
| Quartz 2D (Core Graphics) | 中層 | C | 矢量繪製、路徑、陰影、漸變、圖片生成、PDF | 自定義 View 繪製、圖表、簽名、海報生成 |
| Core Animation | 中高層 | OC/C | 圖層樹合成、隱式/顯式動畫、3D 變換、粒子系統 | 所有 UI 動畫、轉場、複雜視覺效果 |
| UIKit | 最高層 | OC/Swift | 控件封裝、事件響應、佈局系統、文本排版 | 標準 App 界面構建 |
**所有繪製最終都發生在 UIView 的圖層上下文中。** 無論使用哪種引擎,最終輸出都是提交到 CALayer 由 Core Animation 合成顯示。
hidden = NO 從隱藏變顯示。setNeedsDisplay 或 setNeedsDisplayInRect:。contentMode = UIViewContentModeRedraw 時 bounds 改變觸發重繪。- (void)drawRect:(CGRect)rect {
// 1. 獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 繪製路徑/圖形
CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
CGContextFillRect(ctx, CGRectMake(10, 10, 100, 100));
// 3. 繪製文本
NSString *text = @"Hello Quartz";
[text drawAtPoint:CGPointMake(20, 130) withAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:18]}];
// 4. 繪製圖片
[image drawInRect:CGRectMake(20, 160, 100, 100)];
}
setNeedsDisplayInRect: 傳入實際變化的小矩形,而非整個 bounds。opaque = YES,系統跳過混合合成,極大提升滾動性能。UITableView/UICollectionView 復用 Cell,避免重複創建銷毀。view.clearsContextBeforeDrawing = NO,滾動過程中保留上一幀內容,僅繪制增量區域(需自行管理髒矩形)。修改 CALayer 可動畫屬性(position、bounds、transform、opacity、cornerRadius、borderWidth 等)會自動產生隱式動畫(默認 0.25s)。
// 禁用隱式動畫
[CATransaction begin];
[CATransaction setDisableActions:YES];
layer.position = newPosition; // 瞬間跳轉
[CATransaction commit];
UIView 重寫 drawRect:(CPU 繪製)或 CALayer 設置 contents(GPU 紋理)。CAReplicatorLayer、CAEmitterLayer、CAShapeLayer、CAGradientLayer 組合。Metal / OpenGL ES 直接編寫著色器。圖形體系層層疊加,選對層級、用對工具,性能與體驗雙贏。