在 iOS 上要畫出自訂圖形,常見作法有三種,差別在於「畫布從哪裡來」以及「畫完之後交給誰」。
最直覺的方式。系統在呼叫 drawRect: 之前,會自動建立一張與該 view 對應的畫布(CGContext),並把它推入堆疊頂端;方法執行完畢後,系統再自動把它 pop 出去。因此你在方法內只需呼叫 UIGraphicsGetCurrentContext() 就能拿到畫布。
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor);
CGContextFillPath(ctx);
}
若目的是產生一張 UIImage,而不是直接畫在畫面上,就用這個方式。
UIGraphicsBeginImageContextWithOptions(CGSize size, // 畫布尺寸
BOOL opaque, // 是否不透明
CGFloat scale);// 縮放比例,傳 0 代表依螢幕自動匹配
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0); UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)]; [[UIColor blueColor] setFill]; [path fill]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(100, 100, image.size.width, image.size.height); [self.view addSubview:imageView];
scale 參數與 UIImage 的 scale 概念相同,設為 0 時系統會採用目前的螢幕倍率,Retina 螢幕下畫出來才不會模糊。
drawLayer:inContext: 是 CALayer 的代理方法,繪圖邏輯寫在自訂的 delegate 物件中,並搭配 setNeedsDisplay 觸發。
兩個容易踩到的地雷:
drawLayer:inContext:要寫在自訂類別裡。若直接寫在 UIViewController 中,容易出現記憶體過度釋放而崩潰。- 不要把 UIView 本身設為另一個 layer 的 delegate。UIView 已經是自身隱式 layer 的代理,再兼任其他 layer 的 delegate 會導致責任衝突。
@interface LayerDelegate : NSObject @end @interface LayerDelegateView : UIView @end
@implementation LayerDelegate
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 100));
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
CGContextFillPath(ctx);
}
@end
@interface LayerDelegateView ()
@property (strong, nonatomic) LayerDelegate *delegate;
@end
@implementation LayerDelegateView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
CALayer *myLayer = [CALayer layer];
self.delegate = [[LayerDelegate alloc] init];
myLayer.delegate = self.delegate;
myLayer.backgroundColor = [UIColor brownColor].CGColor;
myLayer.bounds = CGRectMake(0, 0, 200, 150);
myLayer.anchorPoint = CGPointZero;
myLayer.position = CGPointMake(100, 100);
myLayer.cornerRadius = 20;
myLayer.shadowColor = [UIColor blackColor].CGColor;
myLayer.shadowOffset = CGSizeMake(10, 20);
myLayer.shadowOpacity = 0.6;
[myLayer setNeedsDisplay]; // 少了這行,drawLayer:inContext: 不會被呼叫
[self.layer addSublayer:myLayer];
}
return self;
}
@end
CGContext 存在系統維護的繪圖上下文堆疊中。你可以把目前的上下文 push 起來暫存,切換去畫另一張圖,畫完再 pop 回原本的上下文繼續作畫。這在「一份畫布要分多次、多階段完成」時特別好用。
UIImage *img1, *img2;
// 上下文 1
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0);
[@"第一個" drawInRect:CGRectMake(10, 20, 80, 20)
withAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsPushContext(UIGraphicsGetCurrentContext()); // 暫存
UIGraphicsEndImageContext();
// 上下文 2
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0);
[@"第二個" drawInRect:CGRectMake(10, 20, 80, 20)
withAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
img2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 回到上下文 1 繼續畫
UIGraphicsPopContext();
[@"再第一個" drawInRect:CGRectMake(110, 20, 80, 20)
withAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
理解 push / pop 的順序是關鍵:push 是「把現有的存起來」,pop 是「把存起來的拿回來」。順序錯了,就會畫到不是你預期的那張畫布上。
三種方式怎麼選?只需要在畫面上呈現自訂圖形,用 drawRect:;要產生一張圖片供後續使用或快取,用 Image Context;繪圖邏輯想獨立出來、讓多個 layer 共用,則 delegate 方式最靈活。