ios截屏事件监听

时间:2022-09-18 00:40:18

目的:实现截屏反馈,类似支付宝的截屏上传反馈功能.

1.注册全局通知,在Appdelegate中注册截屏监听通知

- (void)registNotification{

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];

}

  

2.实现通知

- (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);
}