這篇文章會帶大家把 iOS 繪圖的基本功練起來,涵蓋的內容相當全面:用程式碼畫線段、繪製文字、貼圖片,再到裁剪、重繪,最後甚至能做出簡單的動畫效果。
當我們自訂 view 的時候,系統會自動幫我們呼叫 drawRect 方法,所有繪圖的動作都在這裡發生。
先從最基礎的線段開始。核心觀念是取得圖形上下文,接著拼接路徑,最後渲染顯示:
-(void)drawRect:(CGRect)rect {
// 1. 獲得圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 拼接圖形(路徑)
// 設置線段寬度
CGContextSetLineWidth(ctx, 10);
// 設置線段頭尾部的樣式
CGContextSetLineCap(ctx, kCGLineCapRound);
// 設置線段轉折點的樣式
CGContextSetLineJoin(ctx, kCGLineJoinRound);
/** 第 1 根線段 **/
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1); // 設置顏色
CGContextMoveToPoint(ctx, 10, 10); // 設置起點
CGContextAddLineToPoint(ctx, 100, 100); // 添加線段到 (100,100)
CGContextStrokePath(ctx); // 渲染一次
/** 第 2 根線段 **/
CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1);
CGContextMoveToPoint(ctx, 200, 190);
CGContextAddLineToPoint(ctx, 150, 40);
CGContextAddLineToPoint(ctx, 120, 60);
// 3. 渲染顯示到 view 上面
CGContextStrokePath(ctx);
}
圓弧的繪製需要指定圓心座標、半徑、起訖角度以及伸展方向:
void drawArc() {
// 1. 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 畫圓弧
// x\y: 圓心, radius: 半徑
// startAngle: 開始角度, endAngle: 結束角度
// clockwise: 伸展方向 (0: 順時針, 1: 逆時針)
CGContextAddArc(ctx, 100, 100, 50, M_PI_2, M_PI, 0);
// 3. 顯示所繪制的東西
CGContextFillPath(ctx);
}
void drawCircle() {
// 1. 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 畫圓
CGContextAddEllipseInRect(ctx, CGRectMake(50, 10, 100, 100));
CGContextSetLineWidth(ctx, 10);
// 3. 顯示所繪制的東西
CGContextStrokePath(ctx);
}
void draw4Rect() {
// 1. 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 畫矩形
CGContextAddRect(ctx, CGRectMake(10, 10, 150, 100));
// set: 同時設置實心和空心顏色
// setStroke: 設置空心顏色
// setFill: 設置實心顏色
[[UIColor whiteColor] set];
// 3. 繪制圖形
CGContextFillPath(ctx);
}
三角形需要用 CGContextClosePath 把起點和終點連起來,形成封閉圖形:
void drawTriangle() {
// 1. 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 畫三角形
CGContextMoveToPoint(ctx, 0, 0);
CGContextAddLineToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 150, 80);
CGContextClosePath(ctx); // 關閉路徑
CGContextSetRGBStrokeColor(ctx, 0, 1, 0, 1);
// 3. 繪制圖形
CGContextStrokePath(ctx);
}
繪製文字時,透過屬性字典來指定字體與顏色,再將文字畫進指定的矩形區域:
void drawText() {
// 1. 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 畫矩形
CGRect cubeRect = CGRectMake(50, 50, 100, 100);
CGContextAddRect(ctx, cubeRect);
CGContextFillPath(ctx);
// 4. 畫文字
NSString *str = @"哈哈哈哈 Good morning hello hi hi hi hi";
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
// NSForegroundColorAttributeName: 文字顏色
// NSFontAttributeName: 字體
attrs[NSForegroundColorAttributeName] = [UIColor redColor];
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:50];
[str drawInRect:cubeRect withAttributes:attrs];
}
void drawImage() {
// 1. 取得圖片
UIImage *image = [UIImage imageNamed:@"me"];
// 2. 畫(三種方式擇一)
// [image drawAtPoint:CGPointMake(50, 50)];
// [image drawInRect:CGRectMake(0, 0, 150, 150)];
[image drawAsPatternInRect:CGRectMake(0, 0, 200, 200)];
// 3. 畫文字
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);
// 第 1 根線
CGContextMoveToPoint(ctx, 50, 50);
CGContextAddLineToPoint(ctx, 120, 190);
CGContextStrokePath(ctx);
// 將堆疊頂的上下文出堆疊,替換當前上下文
CGContextRestoreGState(ctx);
CGContextRotateCTM(ctx, M_PI_4 * 0.3);
CGContextScaleCTM(ctx, 0.5, 0.5);
CGContextTranslateCTM(ctx, 0, 150);
裁剪的核心思路其實很單純,就是限制 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 持續觸發重繪,做出類似下雪落下的效果:
-(void)awakeFromNib {
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
-(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)];
}
如果想要更精細地控制多個圖形,也可以改用 CGMutablePathRef 來拼接多條路徑,再一起渲染。使用完畢後別忘了呼叫 CGPathRelease 釋放資源:
-(void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 1. 創建路徑
CGMutablePathRef linePath = CGPathCreateMutable();
CGPathMoveToPoint(linePath, NULL, 0, 0);
CGPathAddLineToPoint(linePath, NULL, 100, 100);
CGContextAddPath(ctx, linePath);
CGMutablePathRef circlePath = CGPathCreateMutable();
CGPathAddArc(circlePath, NULL, 150, 150, 50, 0, M_PI * 2, 0);
CGContextAddPath(ctx, circlePath);
// 4. 渲染
CGContextStrokePath(ctx);
CGPathRelease(linePath);
CGPathRelease(circlePath);
}