ios 图像的内容大小问题

gg0vcinb  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(100)

我试图将视图渲染为图像,但是,我注意到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)
        }
    }
}

omvjsjqw

omvjsjqw1#

设置图像的高度;

let aspectRatio = data.postPic.size.width / data.postPic.size.height
                    let calculatedHeight = UIScreen.main.bounds.width / aspectRatio

                    Image(uiImage: data.postPic)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: UIScreen.main.bounds.width, height: calculatedHeight)

字符串

相关问题