當自訂 view 需要呈現標準元件做不到的視覺時,就得下來到 Core Graphics 這一層。 custom view 被系統加入畫面時,UIView 會自動呼叫 -drawRect:,我們所有的繪製程式碼都寫在那裡。
本文涵蓋:畫線、畫文字、畫圖片、裁剪、變換、狀態堆疊與簡單動畫。
- (void)drawRect:(CGRect)rect
{
// 1. 取得圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 設定線寬與端點/轉折樣式
CGContextSetLineWidth(ctx, 10);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineJoin(ctx, kCGLineJoinRound);
// 第一根線段(紅色)
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
CGContextMoveToPoint(ctx, 10, 10);
CGContextAddLineToPoint(ctx, 100, 100);
CGContextStrokePath(ctx);
// 第二根線段(藍色,兩個轉折點)
CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1);
CGContextMoveToPoint(ctx, 200, 190);
CGContextAddLineToPoint(ctx, 150, 40);
CGContextAddLineToPoint(ctx, 120, 60);
// 3. 渲染到 view 上
CGContextStrokePath(ctx);
}
CGContextStrokePath 會把目前路徑描邊並清空路徑,因此畫完一筆要再畫下一筆時,必須重新 MoveToPoint。若只想描邊不填充用 StrokePath,只填充不描邊用 FillPath,兩者都要則用 CGContextDrawPath(ctx, kCGPathFillStroke)。
/** 畫圓弧 */
void drawArc()
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
// x, y:圓心座標;radius:半徑
// startAngle / endAngle:起訖角度(弳度)
// clockwise:0 為順時針,1 為逆時針
CGContextAddArc(ctx, 100, 100, 50, M_PI_2, M_PI, 0);
CGContextFillPath(ctx);
}
/** 畫圓 */
void drawCircle()
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(50, 10, 100, 100));
CGContextSetLineWidth(ctx, 10);
CGContextStrokePath(ctx);
}
注意 Core Graphics 的座標系原點在左下角,y 軸向上;而 UIKit 的 view 座標系原點在左上角、y 軸向下。在 drawRect: 中,CGContext 已經被轉換為 UIKit 的上下方向,所以直接用 CGRect 那套座標思考即可,但角度的正負方向仍可能讓人困惑,實作時建議畫出來看。
/** 畫矩形 */
void draw4Rect()
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddRect(ctx, CGRectMake(10, 10, 150, 100));
// [UIColor set] 會同時設定填色與描邊色
// setFill 只設填色,setStroke 只設描邊色
[[UIColor whiteColor] set];
CGContextFillPath(ctx);
}
/** 畫三角形 */
void drawTriangle()
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 0, 0);
CGContextAddLineToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 150, 80);
// 關閉路徑:自動連回起點,否則不會有第三條邊
CGContextClosePath(ctx);
CGContextStrokePath(ctx);
}
void drawText()
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 先畫一個底框
CGRect cubeRect = CGRectMake(50, 50, 100, 100);
CGContextAddRect(ctx, cubeRect);
CGContextFillPath(ctx);
// 再以你要的樣式畫字
NSString *str = @"哈哈哈哈Good morning hello hi hi hi hi";
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor redColor]; // 文字顏色
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:50]; // 字型
[str drawInRect:cubeRect withAttributes:attrs];
}
drawInRect:withAttributes: 會在矩形內自動換行;drawAtPoint:withAttributes: 則從指定點開始不換行。這兩個是 NSString 的 UIStringDrawing 方法。
void drawImage()
{
UIImage *image = [UIImage imageNamed:@"me"];
// 三種畫法:
// [image drawAtPoint:CGPointMake(50, 50)]; // 原尺寸,從指定點開始
// [image drawInRect:CGRectMake(0, 0, 150, 150)]; // 拉伸到指定矩形
[image drawAsPatternInRect:CGRectMake(0, 0, 200, 200)]; // 當作平鋪填色使用
NSString *str = @"為xxx所畫";
[str drawInRect:CGRectMake(0, 180, 100, 30) withAttributes:nil];
}
繪製時最麻煩的事莫過於:設了 ctx 的顏色之後,再畫別的圖形就得記得改回來。解法是把當前的繪圖狀態壓入堆疊,用完再彈回:
// 把 ctx 狀態拷貝一份進堆疊
CGContextSaveGState(ctx);
// 這一連串設定只在本次繪製有效
CGContextSetLineWidth(ctx, 10);
[[UIColor redColor] set];
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextMoveToPoint(ctx, 50, 50);
CGContextAddLineToPoint(ctx, 120, 190);
CGContextStrokePath(ctx);
// 堆疊頂端出棧,還原成之前的狀態
CGContextRestoreGState(ctx);
除了顏色,SaveGState 也會保存裁剪區域、變換矩陣、透明度等所有繪圖參數,是組織複雜繪製邏輯的必備工具。
CGContextRotateCTM(ctx, M_PI_4 * 0.3); // 旋轉
CGContextScaleCTM(ctx, 0.5, 0.5); // 縮放
CGContextTranslateCTM(ctx, 0, 150); // 平移
CTM(Current Transformation Matrix)的套用順序會影響結果,且變換是相對目前狀態累加的。實務上幾乎都會搭配 SaveGState / RestoreGState 使用,避免污染後續繪製。
裁剪的思路是「限制 ctx 的顯示區域」,只有落在路徑內的內容才會被畫出來:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
// 0. 先畫一個圓當作裁剪路徑
CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 50, 50));
CGContextClip(ctx); // 以目前路徑設定裁剪區域
CGContextFillPath(ctx);
// 1. 畫圖片,超出圓的部分不會顯示
UIImage *image = [UIImage imageNamed:@"me"];
[image drawAtPoint:CGPointMake(100, 100)];
CGContextRestoreGState(ctx); // 還原裁剪區域
// 這裡的內容不受裁剪影響
CGContextAddRect(ctx, CGRectMake(0, 0, 50, 50));
CGContextFillPath(ctx);
}
CADisplayLink 本質上是一個與螢幕刷新同步的計時器,它的優勢是刷新頻率與顯示器一致,不會產生畫面撕裂。搭配 -setNeedsDisplay 觸發重繪,就能做出流暢的逐幀動畫:
- (void)awakeFromNib
{
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self
selector:@selector(setNeedsDisplay)];
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
// 若不需要與刷新同步,用 NSTimer 也行:
// [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
// selector:@selector(setNeedsDisplay)
// userInfo:nil repeats:YES];
}
- (void)drawRect:(CGRect)rect
{
self.snowY += 5;
if (self.snowY >= rect.size.height) {
self.snowY = -100; // 超出下緣就從上方重新出現
}
UIImage *image = [UIImage imageNamed:@"snow.jpg"];
[image drawAtPoint:CGPointMake(0, self.snowY)];
}
不要在 drawRect: 裡做重活。這個方法在主執行緒執行,且每次重繪都會再跑一次。讀檔、解 JSON、網路請求都不該出現在這裡。
只有需要才實作 drawRect:。實作了它就代表放棄 CALayer 的硬體加速路徑。如果只是顯示圖片或文字,用 UIImageView/UILabel 效能更好。
Considerations for retina。Core Graphics 繪製會自動依 contentScaleFactor 放大,因此不需要手動處理 @2x/@3x;但如果你用 UIGraphicsBeginImageContext 建立離屏 context,記得改用 UIGraphicsImageRenderer(iOS 10+)以自動取得正確的螢幕比例。
動畫首選 Core Animation。能用 layer 屬性動畫達到的效果,就不必用重繪。逐幀重繪成本高,只適合無法用屬性動畫表達的客製視覺。