有時候我們需要把畫面上某一塊視圖存成圖片,例如產生分享海報、把一段簽名區存起來,或做截圖後加工。做法是把 view 的 layer 渲染到一個 bitmap context 中,再取出 UIImage。
#pragma mark view 轉換為 image
+ (UIImage *)imageWithUIView:(UIView *)view {
// 建立一個 bitmap context,並設為目前的繪圖環境
UIGraphicsBeginImageContext(view.bounds.size);
CGContextRef currnetContext = UIGraphicsGetCurrentContext();
// 把 view 的 layer 渲染進去
[view.layer renderInContext:currnetContext];
// 從目前 context 產出圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 將 context 移出堆疊
UIGraphicsEndImageContext();
return image;
}
UIImage *snap = [MyClass imageWithUIView:self.contentView];
1. 必須已完成版面配置。如果在 viewDidLoad 就呼叫,視圖可能還沒算出正確的 frame,截出來的圖會是空白或尺寸錯誤。建議在 viewDidLayoutSubviews 之後或使用者觸發操作時才做。
2. 高解析度版本。上面用的是 UIGraphicsBeginImageContext,在 Retina 螢幕上產出的圖只有一半解析度。若要清晰一點,改用 UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0),第三個參數傳 0 會自動採用螢幕 scale。
3. 漸層、陰影與 cornerRadius 需要額外處理。renderInContext: 對某些由 Core Animation 產生的視覺效果支援有限,例如 CALayer 的 shadow 常常不會被渲染進去。遇到這種情況,可在渲染前先手動把背景色或陰影畫進 context。
4. iOS 10 之後的簡便寫法。可以直接用 UIGraphicsImageRenderer,程式碼更短且自動處理 scale:
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:view.bounds];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
}];
其中 drawViewHierarchyInRect:afterScreenUpdates: 是真正的「畫面快照」,對 layer 效果的還原度比 renderInContext: 更好,代價是效能略低一些。