寫作本身就是一種整理,能避免思維生鏽。這個功能很常見——把當前畫面存成圖片再寫入相簿,無論是分享戰績、保存海報還是做回饋截圖都用得上。
// 截圖
- (UIImage *)captureCurrentView:(UIView *)view {
CGRect frame = view.frame;
UIGraphicsBeginImageContext(frame.size);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
[view.layer renderInContext:contextRef];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *saveImage = [UIImage imageWithCGImage:
CGImageCreateWithImageInRect(image.CGImage,
CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))];
return saveImage;
}
流程是:開一個 bitmap 上下文 → 取得 CGContextRef → 把 view 的 layer 渲染進去 → 取出圖片 → 關閉上下文。最後再用 CGImageCreateWithImageInRect 裁出需要的區域。
// 保存圖片
- (void)saveImageToPhotos:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self,
@selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 保存回調
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo {
NSString *msg = nil;
if (error != NULL) {
msg = @"保存圖片失敗";
} else {
msg = @"保存圖片成功";
}
NSLog(@"%@", msg);
}
上面的程式可以跑,但有三個地方值得改進:
UIGraphicsBeginImageContext 在 Retina 螢幕上會產生 1x 的低解析度圖,文字看起來模糊。改用 UIGraphicsBeginImageContextWithOptions(size, NO, 0.0),第三個參數傳 0 會自動採用螢幕的 scale。CGImageCreateWithImageInRect 建立的 CGImage 屬於 Core Graphics 物件,需由你自行 CGImageRelease,ARC 不會代管。UIImageWriteToSavedPhotosAlbum 不會引發錯誤;但從 iOS 9 之後若使用 PHPhotoLibrary,必須在 Info.plist 補上 NSPhotoLibraryAddUsageDescription,否則會直接崩潰。如果要截取的是整個畫面(包含狀態列)而非單一 view,也可以直接傳入 self.view.window 或 keyWindow,並注意裁切範圍要涵蓋狀態列高度。