我试图将视图渲染为图像,但是,我注意到intrinsicConntentSize的高度值包含了我试图渲染的视图中图像的原始高度,尽管它被缩小了。
例如,如果我有一个高度为4,000 px的图像,但它在视图中显示为~ 400 px,intrinsicContentSize仍然会认为它有4,000像素,这意味着扩展生成的视图图像高度巨大。
我如何修正intrinsicContentSize计算或修改图像,而不会产生巨大的输出图像?
视图中的图像:
Image(uiImage: data.postPic)
.resizable()
.scaledToFit()
.frame(maxWidth: UIScreen.main.bounds.width)
字符串
扩展名:
extension View {
var asImage: UIImage {
let controller = UIHostingController(rootView: self.edgesIgnoringSafeArea(.top))
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
print(targetSize)
view?.bounds = CGRect(origin: CGPoint(x: 0, y: 0), size: targetSize)
view?.backgroundColor = .clear
let format = UIGraphicsImageRendererFormat()
format.scale = 3
let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
型
1条答案
按热度按时间omvjsjqw1#
设置图像的高度;
字符串