首页 > 解决方案 > 在 iOS 14+ 上将 SwiftUI 视图转换为 UIImage

问题描述

我可以使用下面的代码将任何 SwiftUI 视图转换为高分辨率的 UIImage。它工作得很好......直到......我尝试使用大于 CGSize(宽度:2730,高度:2730)的图像尺寸。

如果我将图像大小增加到 CGSize(width: 2731, height: 2731) 或更大,则该行:

self.drawHierarchy(in: self.layer.bounds, afterScreenUpdates: true)

在“扩展 UIView”中,不能再绘制 UIImage。

关于为什么有尺寸限制的任何想法?

注意:我可以通过取消注释“扩展视图”中的 2 行并替换:

self.drawHierarchy(in: self.layer.bounds, afterScreenUpdates: true)

和:

layer.render(in: context.cgContext)

在“扩展 UIView”... 但是 THEN “layer.render” 不会渲染图像效果,例如“模糊”、SceneKit 子视图或金属。所以使用“self.drawHierarchy”是必须的。

// 1: Set breakpoint on line: print("done") to inspect the high res image
// 2: Run, then tap the image on screen to inspect the highresImage
// 3: repeat after changing the size to CGSize = CGSize(width: 2731, height: 2731)

import SwiftUI

struct ContentView: View {
    @State var blurRadius: CGFloat = 4.0
    let imageSize: CGSize = CGSize(width: 2730, height: 2730)

    var body: some View {
        testView
            .frame(width: 300, height: 300)
            .onTapGesture {
                // Adjust blur radius based on high res image scale
                blurRadius *= imageSize.width * 0.5/300

                // Capture high res image of swiftUI view
                let highresImage = testView.asImage(size: imageSize)
                // set breakpoint here to inspect the high res image size, quality, etc.
                print("done")
                
                // reset blur radius back to 4
                blurRadius = 4
            }
    }

    var testView: some View {
        ZStack {
            Color.blue
            Circle()
                .fill(Color.red)
        }
        .blur(radius: blurRadius)
    }
}

extension UIView {
    func asImage() -> UIImage {
        let format = UIGraphicsImageRendererFormat()
        format.scale = 1
        return UIGraphicsImageRenderer(size: self.layer.frame.size, format: format).image { context in
            self.drawHierarchy(in: self.layer.bounds, afterScreenUpdates: true)
            //layer.render(in: context.cgContext)

        }
    }
}


extension View {
    func asImage(size: CGSize) -> UIImage {
        let controller = UIHostingController(rootView: self)
        controller.view.bounds = CGRect(origin: .zero, size: size)
        //UIApplication.shared.windows.first!.rootViewController?.view.addSubview(controller.view)
        let image = controller.view.asImage()
        //controller.view.removeFromSuperview()
        return image
    }
}

标签: viewswiftuiuiimageuigraphicsimagerenderer

解决方案


我不知道为什么,但是在将视图原点的 y 坐标更改为非零之后,它对我有用。这可能是UIHostingController.

如果您使用非常小的Int,则看不到差异,例如:

controller.view.bounds = CGRect(origin: CGPoint(x: 0, y: 0.0001), size: size)

推荐阅读