要把畫面存成圖片,流程是:把 view 的 layer 渲染進一個 bitmap context,取出 UIImage,需要時再裁切,最後同時存進相簿與 App 沙盒。
// 截屏
static int i = 0;
- (IBAction)screenShot:(id)sender {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0);
[[self.window layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = viewImage.CGImage;
// 這裡可以指定想截取的區域
CGRect rect = CGRectMake(166, 211, 426, 320);
CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil); // 存到照片庫
NSData *imageViewData = UIImagePNGRepresentation(sendImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pictureName = [NSString stringWithFormat:@"screenShow_%d.png", i];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];
NSLog(@"%@", savedImagePath);
[imageViewData writeToFile:savedImagePath atomically:YES]; // 存到沙盒
CGImageRelease(imageRefRect);
i++;
}
用 scale 而非寫死尺寸。 UIGraphicsBeginImageContextWithOptions 的第三個參數傳 0 代表使用裝置的螢幕 scale,這樣在 Retina 機型上才不會拿到模糊圖。範例把尺寸寫死成 640×960,在 iPhone 5 上剛好,換機型就會出錯。建議直接用 UIScreen.mainScreen.bounds.size 或要截的那個 view 的 bounds.size。
裁切座標的單位是點還是像素要對齊。 CGImageCreateWithImageInRect 吃的是 CGImage 的像素座標。若你的 context 是 2 倍解析度,畫面上 (166, 211) 這一點在 CGImage 裡其實是 (332, 422)。裁出來位置不對,十之八九是這裡沒換算。
Core Graphics 的 Create 要對應 Release。 CGImageCreateWithImageInRect 遵循 Create Rule,用完必須 CGImageRelease,否則在 MRC 環境會漏記憶體。ARC 不會幫你管理 CG 物件。
存相簿需要權限。 正式專案請先檢查 ALAssetsLibrary(或 iOS 9 之後的 PHPhotoLibrary)的授權狀態,使用者拒絕過的話 UIImageWriteToSavedPhotosAlbum 會靜默失敗。同時 Info.plist 要補上 NSPhotoLibraryUsageDescription,否則會直接崩潰。
檔名遞增計數只是範例。 用 static 變數命名重複啟動就會覆寫。實務上建議用 NSTimeInterval 時間戳或 NSUUID 產生檔名。