UIGraphicsBeginImageContext不返回视网膜图像

时间:2017-08-19 19:28:50

标签: ios swift screenshot

我想捕捉图像中的当前屏幕。我这样做:

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 Plus和7 Plus。无论我输入比例参数,输出始终是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。我究竟做错了什么?如何获得更高分辨率的图像?

3 个答案:

答案 0 :(得分:1)

这段代码可以解决问题

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 不关心规模,只关心尺寸。

修改

您可能希望使用iOS 10及更高版本中提供的较新的API

let renderer = UIGraphicsImageRenderer(bounds: self.view.bounds)

let snapshot = renderer.image(actions: { context in
    self.view.layer.render(in: context.cgContext)
})

答案 1 :(得分:0)

快照UIImage,有两个属性sizescale;很像屏幕。要确定图像的实际像素大小,必须将大小乘以比例。我认为你的问题是你假设size属性是像素而不是点。

  

size
  图像的逻辑尺寸,以点为单位。

您可以使用UIImageJPEGRepresentation创建JPG并将其保存到磁盘以使用您熟悉的图像工具进行检查,从而以非常明确的方式对此进行测试。

答案 2 :(得分:0)

问题在于你的期望是错误的;你不明白什么是分辨率。对于1x图像,其对应的2x图像及其对应的3x图像,size是相同的。不同的是图像scale;如果你看一下,你会发现它变化正确。

如果您想自己证明这一点,请将UIImage转换为CGImage并查看的大小。现在您可以看到底层位图的尺寸。