UIGraphicsBeginImageContext不返回视网膜图像
问题描述:
我想捕获图像中的当前屏幕。我这样做:UIGraphicsBeginImageContext不返回视网膜图像
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false)
let snapshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
问题是规模参数。如果我理解正确,0.0代表非视网膜,2.0代表视网膜,3.0代表6加和7加视网膜。无论我输入到scale参数中,输出始终是375x667分辨率的图像。我也尝试了不同的方法:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale)
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
同样的情况。我甚至使用
UIScreen.main.scale
这实际上回报价值2.0。我究竟做错了什么?我如何获得更高分辨率的图像?
答
此代码将这样的伎俩
let contextSize = CGSize(width: self.view.bounds.size.width * UIScreen.main.scale, height: self.view.bounds.size.height * UIScreen.main.scale)
UIGraphicsBeginImageContextWithOptions(contextSize, self.view.isOpaque, UIScreen.main.scale)
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
CGContext不关心规模,它关心的只是大小。
编辑
您可能需要使用可用的新API iOS中10及更高版本
let renderer = UIGraphicsImageRenderer(bounds: self.view.bounds)
let snapshot = renderer.image(actions: { context in
self.view.layer.render(in: context.cgContext)
})
答
快照是UIImage
它有两个属性,size
和scale
;很像屏幕。要确定图像像素的实际大小,您必须将大小乘以比例。我认为你的问题是你认为size属性是像素而不是点。
size
图像的逻辑尺寸,以点为单位。
您可以通过使用UIImageJPEGRepresentation
创建JPG,并将其保存到磁盘在一个非常明确的方式测试这种使用图像工具你熟悉检查。
答
问题是你的期望是错误的;你不明白什么是解决方案。 size
对于1x图像,其相应的2x图像及其对应的3x图像是相同的。不同之处在于图片的scale
;如果你看一下,你会发现它是正确的。
如果你想证明这一点你自己,将UIImage转换为CGImage并看看的大小。现在您可以看到底层位图的尺寸。
实际上,0.0表示实际的屏幕比例,而不是非视网膜。那是1.0。 – the4kman
你如何确定最终图像的“大小”? –
“分辨率”是什么意思?唯一不同的是UIImage的“scale”。尺寸以点为单位,而不是像素;所有的比例都是一样的。 – matt