//添加截屏监听
[[NSNotificationCenterdefaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
// executes after screenshot
NSLog(@"截屏");
[self imageWithScreenshot];
}];
/**
* 截取当前屏幕
*
*/
- (UIImage *)imageWithScreenshot
{
CGSize imageSize =CGSizeZero;
UIInterfaceOrientation orientation = [UIApplicationsharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsPortrait(orientation))
imageSize = [UIScreenmainScreen].bounds.size;
else
imageSize = CGSizeMake([UIScreenmainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
UIGraphicsBeginImageContextWithOptions(imageSize,NO, 0);
CGContextRef context =UIGraphicsGetCurrentContext();
for (UIWindow *windowin [[UIApplicationsharedApplication] 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 (orientation ==UIInterfaceOrientationLandscapeLeft)
{
CGContextRotateCTM(context,M_PI_2);
CGContextTranslateCTM(context,0, -imageSize.width);
}
elseif (orientation ==UIInterfaceOrientationLandscapeRight)
{
CGContextRotateCTM(context, -M_PI_2);
CGContextTranslateCTM(context, -imageSize.height,0);
} elseif (orientation ==UIInterfaceOrientationPortraitUpsideDown) {
CGContextRotateCTM(context,M_PI);
CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
}
if ([windowrespondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
[window drawViewHierarchyInRect:window.boundsafterScreenUpdates:YES];
}
else
{
[window.layerrenderInContext:context];
}
CGContextRestoreGState(context);
}
UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimage;
}