截屏需求的本質是「把畫面渲染到一張離屏畫布上,再取出成圖」。本文示範完整流程,並補上裁切特定區域與兩種保存方式的處理。
- (void)actionShot:(UIButton *)sender {
// 先隱藏自己,避免按鈕被截進畫面
self.buttonShot.hidden = YES;
// 建立與畫面同尺寸的圖形上下文
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(self.view.frame.size.width, self.view.frame.size.height), NO, 0);
// 把 window 的 layer 渲染到目前的上下文
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[delegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
// 取出成品
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.buttonShot.hidden = NO;
// ---- 若只需要畫面中的某個區域 ----
CGImageRef fullImage = screenImage.CGImage;
// 注意 Retina 放大倍率:iPhone 6 Plus 需乘 3,實務上應改為讀取螢幕 scale
CGRect rect = CGRectMake(0, 0,
screenImage.size.width * 3,
screenImage.size.height * 3);
CGImageRef targetImage = CGImageCreateWithImageInRect(fullImage, rect);
UIImage *finalImage = [UIImage imageWithCGImage:targetImage];
// 存到相簿
UIImageWriteToSavedPhotosAlbum(finalImage, self,
@selector(image:didFinishSavingWithError:contextInfo:), nil);
// 存到沙盒 Documents
NSString *dir = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HHmmss";
NSString *name = [NSString stringWithFormat:@"ScreenShot_%@.png",
[fmt stringFromDate:[NSDate date]]];
NSString *path = [dir stringByAppendingPathComponent:name];
[UIImagePNGRepresentation(finalImage) writeToFile:path atomically:YES];
CGImageRelease(targetImage); // Create 建立的物件必須手動釋放
}
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo {
NSString *msg = (error != NULL) ? @"保存圖片失敗" : @"保存圖片成功";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存結果"
message:msg
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
倍率不要寫死。範例中的 *3 只是 iPhone 6 Plus 的情況,iPhone 6 是 2,其他機型又不同。正確做法是讀取 [UIScreen mainScreen].scale 或 screenImage.scale,讓程式自適應。
記得釋放 CGImage。凡是名稱含 Create 或 Copy 的 Core Graphics / Foundation 函式,其回傳值都需自行 CGImageRelease 或 CFRelease,否則會造成記憶體洩漏。
renderInContext: 無法擷取影片畫面。它只能渲染 UIView 的 layer 樹,OpenGL ES、AVPlayer、相機預覽等以 GPU 直接輸出的內容會是黑底。要擷取這類畫面必須改用 CVOpenGLESTextureCache 讀取 GL 緩衝區。
隱藏元素的時機。若直接在截屏前隱藏、截完立刻還原,某些情況下系統尚未完成版面更新。較穩妥的做法是隱藏後呼叫一次 layoutIfNeeded,或把不想被截到的元素放到獨立的 container view 中,截屏時只渲染目標 container。