目的:實現截屏反饋,相似支付寶的截屏上傳反饋功能.windows
1.註冊全局通知,在Appdelegate中註冊截屏監聽通知code
- (void)registNotification{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil]; }
2.實現通知orm
- (void)getScreenshot:(NSNotification *)notification{ NSLog(@"捕捉截屏事件"); UIImage *shorImg = [UIImage imageWithData:[self imageDataScreenShot]]; }
- (NSData *)imageDataScreenShot { CGSize imageSize = CGSizeZero; imageSize = [UIScreen mainScreen].bounds.size; UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); for (UIWindow *window in [[UIApplication sharedApplication] windows]) { CGContextSaveGState(context); CGContextTranslateCTM(context, window.center.x, window.center.y); CGContextConcatCTM(context, window.transform); CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y); if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES]; } else { [window.layer renderInContext:context]; } CGContextRestoreGState(context); } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return UIImagePNGRepresentation(image); }