產(chǎn)品需求:在APP內(nèi)部囱修,當(dāng)監(jiān)聽(tīng)到用戶有截屏行為的時(shí)候想诅,提示用戶進(jìn)行分享APP頁(yè)面吠卷,達(dá)到引流的效果锡垄;
廢話不多說(shuō),直接上效果圖:
具體做法:
- 1.首先在
AppDelegate.m
文件的方法didFinishLaunchingWithOptions
里面設(shè)置監(jiān)聽(tīng)截屏行為
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
- 2.然后做監(jiān)聽(tīng)的處理祭隔,繪制獲取當(dāng)前屏幕的上下文货岭,輸入圖片
- (void)userDidTakeScreenshot:(NSNotification *)notification {
UIImage *image = [self imageWithScreenshot];
if(image) {
// WEGlobalShareView這個(gè)是繪制顯示的效果圖,頁(yè)面不復(fù)雜疾渴,小編就沒(méi)有放到這里來(lái)
[WEGlobalShareView showWithDelegate:self andDetailImage:image];
}
}
// 截取當(dāng)前屏幕 ,返回截取到的圖片
- (UIImage *)imageWithScreenshot {
CGSize imageSize = CGSizeZero;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsPortrait(orientation)) {
imageSize = [UIScreen mainScreen].bounds.size;
} else {
imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
}
// 繪制上下文
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 (orientation == UIInterfaceOrientationLandscapeLeft) {
CGContextRotateCTM(context, M_PI_2);
CGContextTranslateCTM(context, 0, -imageSize.width);
} else if (orientation == UIInterfaceOrientationLandscapeRight) {
CGContextRotateCTM(context, -M_PI_2);
CGContextTranslateCTM(context, -imageSize.height, 0);
} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
CGContextRotateCTM(context, M_PI);
CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
}
if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
} else {
[window.layer renderInContext:context];
}
CGContextRestoreGState(context);
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
return [UIImage imageWithData:imageData];
}
- 3.最后拿到圖片以后千贯,進(jìn)行分享頁(yè)面即可;