iOS 系統內建的控件已經相當強大,但仍有大量場景無法直接滿足需求。這時候就得自己畫。本文把 iOS 繪圖的知識整理成一份可查閱的清單,從圖形上下文講到浮水印、裁切與截圖。
圖形上下文是一個 CGContextRef 型別的資料結構,它負責三件事:

- (void)drawRect:(CGRect)rect 是系統用來讓我們自繪的入口。當控件第一次顯示時被呼叫,參數 rect 就是該控件目前的 bounds。
繪圖的固定流程:
CGContextRef ctx = UIGraphicsGetCurrentContext();常用的路徑拼接函式:
void CGContextMoveToPoint(CGContextRef c, CGFloat x, CGFloat y)
void CGContextAddLineToPoint(CGContextRef c, CGFloat x, CGFloat y)
void CGContextAddRect(CGContextRef c, CGRect rect)
void CGContextAddEllipseInRect(CGContextRef context, CGRect rect)
void CGContextAddArc(CGContextRef c, CGFloat x, CGFloat y,
CGFloat radius, CGFloat startAngle,
CGFloat endAngle, int clockwise)
渲染方式:
void CGContextDrawPath(CGContextRef c, CGPathDrawingMode mode)
void CGContextStrokePath(CGContextRef c) // 只描邊
void CGContextFillPath(CGContextRef c) // 只填充
記法:凡是 CGContextDraw、CGContextStroke、CGContextFill 開頭的函式,都是用來繪製路徑的。
- (void)drawLine {
// 1. 取得與當前 view 關聯的上下文(系統自動建立)
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2. 設定上下文狀態,必須在渲染之前設定
[[UIColor redColor] set];
CGContextSetLineWidth(ctx, 15);
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextSetLineCap(ctx, kCGLineCapRound);
// 3. 拼接路徑:一個 UIBezierPath 可包含多條線
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 125)];
[path addLineToPoint:CGPointMake(220, 125)];
// 未重新 moveToPoint 時,下一段線會從上一段終點接續
[path addLineToPoint:CGPointMake(200, 150)];
// 4. 加入上下文並渲染到 view 的圖層
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
- (void)drawQuadCurve {
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 125)];
[path addQuadCurveToPoint:CGPointMake(240, 125)
controlPoint:CGPointMake(125, 0)];
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
}
- (void)drawRectShape {
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [UIBezierPath
bezierPathWithRoundedRect:CGRectMake(50, 50, 100, 100)
cornerRadius:20];
CGContextAddPath(ctx, path.CGPath);
[[UIColor redColor] setFill];
[[UIColor greenColor] setStroke];
// 同時描邊與填充
CGContextDrawPath(ctx, kCGPathFillStroke);
}
- (void)drawRect:(CGRect)rect {
CGPoint center = CGPointMake(125, 125);
// clockwise: YES 順時針,NO 逆時針
UIBezierPath *path = [UIBezierPath
bezierPathWithArcCenter:center
radius:100
startAngle:0
endAngle:-M_PI_2
clockwise:NO];
[path addLineToPoint:center];
// fill 會自動閉合路徑(從終點連回起點)
[path fill];
}
- (void)drawRect:(CGRect)rect {
NSString *name = @"會長桂雛菊";
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
attr[NSFontAttributeName] = [UIFont systemFontOfSize:15];
attr[NSForegroundColorAttributeName] = [UIColor redColor];
attr[NSStrokeColorAttributeName] = [UIColor redColor];
attr[NSStrokeWidthAttributeName] = @1;
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeMake(3, 3);
shadow.shadowColor = [UIColor yellowColor];
shadow.shadowBlurRadius = 3;
attr[NSShadowAttributeName] = shadow;
[name drawInRect:CGRectMake(90, 100, 100, 50) withAttributes:attr];
}
初始化時系統會呼叫 drawRect: 完成繪製。但如果要重繪,直接呼叫 drawRect: 是無效的,必須改用 setNeedsDisplay。
- (void)drawRect:(CGRect)rect {
NSArray *datas = @[@25, @25, @50];
CGPoint center = CGPointMake(125, 125);
CGFloat r = 100;
CGFloat startA = 0, endA = 0;
for (NSNumber *number in datas) {
startA = endA;
CGFloat angle = number.intValue / 100.0 * M_PI * 2;
endA = startA + angle;
UIBezierPath *path = [UIBezierPath
bezierPathWithArcCenter:center radius:r
startAngle:startA endAngle:endA
clockwise:YES];
[path addLineToPoint:center];
[[self randomColor] set];
[path fill];
}
}
// 點擊時重繪
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self setNeedsDisplay];
}
- (UIColor *)randomColor {
CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1];
}
void CGContextSaveGState(CGContextRef c) // 把目前狀態複製一份壓入堆疊頂
void CGContextRestoreGState(CGContextRef c) // 取出堆疊頂狀態並取代目前狀態
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 橫線:紅色、線寬 10
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 150)];
[path addLineToPoint:CGPointMake(290, 150)];
CGContextAddPath(ctx, path.CGPath);
CGContextSaveGState(ctx); // 保存目前狀態
CGContextSetLineWidth(ctx, 10);
[[UIColor redColor] set];
CGContextStrokePath(ctx);
// 豎線:因為上面已 Restore,這裡恢復成預設的黑色細線
path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(150, 10)];
[path addLineToPoint:CGPointMake(150, 290)];
CGContextAddPath(ctx, path.CGPath);
CGContextRestoreGState(ctx);
CGContextStrokePath(ctx);
}
透過矩陣操作,可以讓之後繪製到上下文中的所有路徑一起變形。
void CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy)
void CGContextRotateCTM(CGContextRef c, CGFloat angle)
void CGContextTranslateCTM(CGContextRef c, CGFloat tx, CGFloat ty)
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [UIBezierPath
bezierPathWithOvalInRect:CGRectMake(-100, -50, 200, 100)];
// 矩陣操作必須在 addPath 之前完成
CGContextTranslateCTM(ctx, 100, 100);
CGContextRotateCTM(ctx, M_PI_4);
CGContextScaleCTM(ctx, 0.5, 0.5);
CGContextAddPath(ctx, path.CGPath);
CGContextFillPath(ctx);
}
相關 API:
// 開啟一個基於位圖的上下文
// size: 尺寸;opaque: 是否不透明;scale: 0 表示不縮放
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
UIImage* UIGraphicsGetImageFromCurrentImageContext() // 取得圖片
void UIGraphicsEndImageContext() // 結束上下文
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"hina"];
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
[image drawAtPoint:CGPointZero];
NSString *str = @"會長桂雛菊";
[str drawAtPoint:CGPointMake(0, 0) withAttributes:nil];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:@"/Users/apple/Desktop/image.png" atomically:YES];
}
關鍵 API 是 void CGContextClip(CGContextRef c):把目前路徑設為裁切區域,超出範圍的內容不會顯示。
思路:先畫一個大圓當外圈,再設定與圖片同尺寸的裁切區域,把圖片畫進去。
+ (UIImage *)imageCircleWithImage:(UIImage *)image
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor {
CGFloat boardW = borderWidth;
CGFloat imageW = image.size.width + 2 * boardW;
CGFloat imageH = image.size.height + 2 * boardW;
// 只有正方形才能內切圓,取較短邊
CGFloat circleW = imageW > imageH ? imageH : imageW;
CGRect rect = CGRectMake(0, 0, circleW, circleW);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 畫外圓
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
CGContextAddPath(ctx, path.CGPath);
[borderColor set];
CGContextFillPath(ctx);
// 設定裁切區域(與圖片同尺寸,但起始座標要加上邊框寬)
rect = CGRectMake(boardW, boardW, image.size.width, image.size.height);
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:rect];
[clipPath addClip];
[image drawInRect:rect];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); // 務必關閉,否則會持續佔用記憶體
return image;
}
View 之所以能顯示內容,完全來自它內部的 layer。drawRect: 中取得的是 Layer 的圖形上下文,所以畫的東西其實是畫到 layer 上。利用這一點就能把整個 view 渲染成一張圖:
- (void)renderInContext:(CGContextRef)ctx;
+ (UIImage *)imageWithCaptureView:(UIView *)captureView {
UIGraphicsBeginImageContextWithOptions(captureView.bounds.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[captureView.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}