如何使用iOS上的代码截取屏幕截图?

问题描述 投票:3回答:2

如何以编程方式截取屏幕截图?

ios uiimage screenshot
2个回答
14
投票

你可以使用UIGraphicsBeginImageContext来达到这个目的。

例如 :

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData*theImageData = UIImageJPEGRepresentation(theImage, 1.0 ); //you can use PNG too
[theImageData writeToFile:@"example.jpeg" atomically:YES];

这里

1.首先,我采用图像上下文,我已经将它作为webview视频的myView给出,你可以提供任何你想要的东西。这将获取可在屏幕上看到的webview图像。

2使用UIGraphicsGetImageFromCurrentImageContext()我将webview的屏幕截图转换为图像。

3.通过使用UIGraphicsEndImageContext(),我要求它结束背景。

我将图像保存到NSData,因为我必须邮寄截图。如果它用于发送或保存,保持在NSData似乎是一个很好的选择。

编辑:要将其添加到相机胶卷,您需要写:

UIImageWriteToSavedPhotosAlbum(theImage,nil,NULL,NULL);之后的UIGraphicsEndImageContext();


1
投票

看看这个answer.It也照顾视网膜显示。

实际上要解释这个过程,

  • 选择图像上下文大小(可能是您需要屏幕截图的图层大小)
  • 在创建的上下文中渲染要截屏的图层
  • 从上下文中获取图像,您就完成了!
© www.soinside.com 2019 - 2024. All rights reserved.