iPhone 自帶的截屏功能已經很好用,一般使用者不會在 App 裡找這個功能。但有幾種情況你非得自己做不可:例如播放器用 OpenGL 渲染影片,系統截屏會把 OSD 疊加層一起拍進去,而你只想要乾淨的影片畫面。
關鍵差異在於:OpenGL 是直接寫進 GPU 的 frame buffer,用一般方式讀 layer 是讀不到的。所以分成兩種情況處理。
- (void)snapshotScreen {
// 檢查是否為 retina 螢幕(iPod 有非 retina 機型)
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(self.view.window.bounds.size, NO,
[UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.view.window.bounds.size);
}
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename = [[path objectAtIndex:0] stringByAppendingPathComponent:@"foo.png"];
[data writeToFile:filename atomically:YES];
}
前半段在判斷 retina,因為 scale 參數會直接影響輸出的像素尺寸;最後把圖存進 App 的 Documents 目錄。
這時候要走 glReadPixels 把 frame buffer 的內容讀出來:
- (void)getGLScreenShot {
int w = self.bounds.size.width;
int h = self.bounds.size.height;
NSInteger myDataLength = w * h * 4;
GLubyte *buffer = (GLubyte *)malloc(myDataLength);
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// OpenGL 的原點在左下,畫面上下顛倒,要翻正
GLubyte *buffer2 = (GLubyte *)malloc(myDataLength);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w * 4; x++) {
buffer2[(h - 1 - y) * w * 4 + x] = buffer[y * 4 * w + x];
}
}
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * w;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef imageRef = CGImageCreate(w, h, bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
UIImageWriteToSavedPhotosAlbum(myImage, self,
@selector(GLImage:didFinishSavingWithError:contextInfo:), buffer2);
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpaceRef);
free(buffer);
}
注意這裡刻意沒有釋放 buffer2:寫入相簿是非同步的,要等 GLImage:didFinishSavingWithError:contextInfo: 回呼時才能清掉。順著這個回呼,也可以在 UI 上做限制,避免使用者連續快速截屏把系統壓垮。
中間那兩層 for 迴圈就是上下翻轉用的,寫法效率不高,但暫時沒找到更好的方式。如果要優化,可以直接改寫 kCGBitmapByteOrder 的組合並搭配 CGContextTranslateCTM,或反過來在建立 CGImage 時就指定 kCGBitmapInfoFloatComponents 相關旗標來避免這份拷貝。
iOS 7 為 UIView 加了 drawViewHierarchyInRect:afterScreenUpdates:,它會把 view 階層「渲染」成點陣圖,因此 OpenGL 內容也一起進來,兩種場景一次搞定:
// 僅支援 iOS 7 以上
- (void)snapshotScreenWithGL {
CGSize size = videoView.bounds.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGRect rec = CGRectMake(videoView.frame.origin.x, videoView.frame.origin.y,
videoView.bounds.size.width, videoView.bounds.size.height);
[self.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename = [[path objectAtIndex:0] stringByAppendingPathComponent:@"foo.png"];
[data writeToFile:filename atomically:YES];
}
afterScreenUpdates: 這個參數值得留意:傳 YES 會先把畫面同步一次再截,能拍到最新狀態但較慢;傳 NO 則直接取目前內容,快但可能是前一帧。做影片截帧時通常傳 NO 比較合適。
如果你要的只是「一張快照」而不是真的檔案,[view snapshotViewAfterScreenUpdates:] 會回傳一個 UIView,成本遠低於轉成 UIImage。適合用在把某個區塊暫時「凍結」當作轉場背景,或做列表 cell 的快取。
最後提醒,若 App 會把截圖存進相簿,別忘了在 Info.plist 加上 NSPhotoLibraryAddUsageDescription;同時在 UI 上做節流,連續截屏不只耗 CPU,也會讓使用者不明的相簿被塞滿檔案。