iOS 可透過 motionBegan 監聽搖晃事件,再呼叫截圖方法。使用前需讓目前視圖控制器成為第一響應者。
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
[self snapshot];
}
}
截圖時先建立圖形上下文,將 view 的 layer 渲染到上下文,再取得 UIImage,最後關閉上下文並存入相簿。
- (void)snapshot {
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
保存完成後會呼叫固定回呼方法,可根據 error 判斷是否成功。