我在捕获自定义 View 时遇到问题。我正在尝试将捕获的图像设置为 UIImage
图像数据的大小,但是当我截取屏幕截图时,图像是这样的! :
图像缩小了! 这是代码:
UIGraphicsBeginImageContextWithOptions((self.photoImage.size), false, UIScreen.main.scale)
self.captureView.layer.render(in: UIGraphicsGetCurrentContext()!)
self.photoToShare = UIGraphicsGetImageFromCurrentImageContext()
print(self.photoToShare.size) //the size is right
UIGraphicsEndImageContext()
self.photo.image = self.photoToShare!
这是什么问题?!
我累了:
self.captureView.drawHierarchy(in:self.captureView.bounds,afterScreenUpdates:true)
还是没有成功
编辑
我试过这个方法,截屏然后裁剪还是不行
UIGraphicsBeginImageContextWithOptions(self.captureView.bounds.size, false, UIScreen.main.scale)
self.captureView.drawHierarchy(in: self.captureView.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let cropRect = CGRect(x: 0, y: 0, width: (self.photoImage.size.width) , height: (self.photoImage.size.height))
UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.main.scale)
image?.draw(in: cropRect)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.photo.image = finalImage
但是图像会失真:
最佳答案
我尝试使用以下方法使用 aspectToFit 内容模式捕获 imageview 的屏幕截图并且没有恒定的宽度和高度
func captureShot() {
let layer : CALayer = self.imageView!.layer
UIGraphicsBeginImageContextWithOptions((layer.frame.size), false, 1.0);
layer.render(in: UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
& 返回的屏幕截图具有相同的图像大小 (229*220),这是图像的原始大小。
关于ios - 根据 UIImage 大小捕获屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931810/