「搖一搖擷取畫面」是很多 App 都有的除錯或分享功能。實作可以拆成兩半:先攔下搖動手勢,再把當前畫面渲染成圖片存進相簿。
1. 讓當前視圖控制器成為第一響應者。少了這一步, motion 事件不會傳到你這裡:
// 必須先成為第一響應者,才能收到 motion 事件 [self becomeFirstResponder];
2. 覆寫 UIResponder 的 motion 方法:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
[self snapshot];
}
}
實務上建議把 becomeFirstResponder 放在 viewDidAppear:,並在 viewWillDisappear: 呼叫 resignFirstResponder,否則畫面切走後仍可能收到搖動事件。另外也要記得實作 canBecomeFirstResponder 回傳 YES。
流程有兩個重點:順序不能顛倒——必須先開啟圖像上下文,再取得它;以及回呼方法的簽名必須固定,didFinishSavingWithError:contextInfo: 的參數型別不可自行更動。
#pragma mark - 點擊截圖按鈕
- (IBAction)snapshot {
// 1. 開啟圖像上下文(務必先執行這步)
UIGraphicsBeginImageContext(self.view.bounds.size);
// 2. 取得目前上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 3. 把視圖圖層渲染進上下文
[self.view.layer renderInContext:context];
// 4. 從上下文取出圖像
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 5. 關閉上下文
UIGraphicsEndImageContext();
// 6. 存入相簿
UIImageWriteToSavedPhotosAlbum(image, self,
@selector(image:didFinishSavingWithError:contextInfo:), nil);
}
#pragma mark - 保存完成後的回呼(簽名固定)
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"儲存失敗 - %@", error.localizedDescription);
} else {
NSLog(@"保存成功");
}
}
UIGraphicsEndImageContext() 一定要呼叫。上下文是有限資源,未釋放會造成記憶體壓力,連續截圖幾次就可能被系統終止。UIGraphicsBeginImageContextWithOptions(size, YES, 0.0),第三個參數傳 0 會自動採用螢幕 scale。info.plist 加上用途說明字串,否則會直接失敗。renderInContext: 無法擷取 CAMetalLayer 或相機預覽等由 GPU 直接合成的内容;這類畫面需要改用 drawViewHierarchyInRect:afterScreenUpdates:。