今天无聊在京东上 逛,想买个机械键盘,看来看去不知道哪个好,就截图微信发给同学请教一下款式如何,索性准备截图微信发给他,当我在京东客户端截完图,自动弹出分享面板,忽然被震到了,这个需求这是很贴心,我们一般截图都是为了用 IM 工具发出去,这样就省了好多步骤,很贴心🈶木🈶.今天就研究了一下,闲言不多说 , 写完博客, 还要看<<人民的名义>>,你懂得😉!

OC(十九)-获取截图通知以及分享截图 - 图1

coreCode如下,我把它放在了 AppDelegate 中

  1. //构建截图通知 UIApplicationUserDidTakeScreenshotNotification
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenShoot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
  3. - (void)screenShoot:(NSNotification * )noti{
  4. [SVProgressHUD showSuccessWithStatus:@"截图成功"];
  5. [UtilsFunctions showShareActionSheet:[UIApplication sharedApplication].keyWindow image:[self createScreenShootImage] urlString:nil];
  6. }

获取截图的图片

  1. /**
  2. 获得截屏的图片
  3. @return 生成的图片
  4. */
  5. - (UIImage *)createScreenShootImage{
  6. //设置 size
  7. UIGraphicsBeginImageContextWithOptions((CGSize){WIDTHOFSCREEN, HEIGHTOFSCREEN}, YES, [UIScreen mainScreen].scale) ;
  8. //获得句柄
  9. CGContextRef ref = UIGraphicsGetCurrentContext();
  10. UIWindow * window = [UIApplication sharedApplication].delegate.window;
  11. //渲染到 context中
  12. [window.layer renderInContext:ref];
  13. //获得想要的图片
  14. UIImage * createdImage = UIGraphicsGetImageFromCurrentImageContext();
  15. UIGraphicsEndImageContext();
  16. return createdImage;
  17. }

特别注意:

这里使用的是UIGraphicsBeginImageContextWithOptions而不是UIGraphicsBeginImageContext,原因是 防止获取的截图的图片模糊,关键参数:UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)中的 scale.