您的位置:首页 > 移动开发 > IOS开发

iOS开发 检测用户截图

2017-08-28 16:05 344 查看
一.介绍

iOS7提供一个崭新的监听用户截图的通知

// This notification is posted after the user takes a screenshot (for example by pressing both the home and lock screen buttons)
UIKIT_EXTERN NSNotificationName const UIApplicationUserDidTakeScreenshotNotification NS_AVAILABLE_IOS(7_0);

二.代码

1.先写一个UIWindow的分类

.h文件

#import <Foundation/Foundation.h>

@interface UIWindow (WLKit)

- (UIImage *)takeScreenshot;
@end

.m文件

#import "UIWindow+WLKit.h"

@implementation UIWindow (WLKit)

- (UIImage *)takeScreenshot
{
BOOL ignoreOrientation = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0");

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

CGSize imageSize = CGSizeZero;
if (UIInterfaceOrientationIsPortrait(orientation) || ignoreOrientation) {
imageSize = [UIScreen mainScreen].bounds.size;
} else {
imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
}

UIGraphicsBeginImageContextWithOptions(imageSize, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, self.center.x, self.center.y);
CGContextConcatCTM(context, self.transform);
CGContextTranslateCTM(context, -self.bounds.size.width * self.layer.anchorPoint.x, -self.bounds.size.height * self.layer.anchorPoint.y);

if (!ignoreOrientation) {
if (orientation == UIInterfaceOrientationLandscapeLeft) {
CGContextRotateCTM(context, (CGFloat)M_PI_2);
CGContextTranslateCTM(context, 0, -imageSize.width);
} else if (orientation == UIInterfaceOrientationLandscapeRight) {
CGContextRotateCTM(context, (CGFloat)-M_PI_2);
CGContextTranslateCTM(context, -imageSize.height, 0);
} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
CGContextRotateCTM(context, (CGFloat)M_PI);
CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
}
}

if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
} else {
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
}

CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}

@end

2.注册通知

// 截屏通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];

3.通知方法

#pragma mark - 截屏通知
- (void)userDidTakeScreenshot:(NSNotification *)not
{
NSLog(@"检测到截屏");
// 获取图片
UIImage *screenshotImage = self.view.window.takeScreenshot;
// 保存图片
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息