有关如何使用view.drawHierarchy(in:)
或view.layer.renderInContext()
将UIView转换为UIImage的讨论。但是,即使将比例设置为设备比例,结果仍然是非常糟糕的分辨率。我想知道是否有办法以高分辨率和高质量将UIView转换为UIImage?
答案 0 :(得分:2)
您需要在每个子视图上设置正确的内容比例。
extension UIView {
func scale(by scale: CGFloat) {
self.contentScaleFactor = scale
for subview in self.subviews {
subview.scale(by: scale)
}
}
func getImage(scale: CGFloat? = nil) -> UIImage {
let newScale = scale ?? UIScreen.main.scale
self.scale(by: newScale)
let format = UIGraphicsImageRendererFormat()
format.scale = newScale
let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: format)
let image = renderer.image { rendererContext in
self.layer.render(in: rendererContext.cgContext)
}
return image
}
}
创建图片:
let image = yourView.getImage()