首页 > 解决方案 > 将 SwiftUI 视图转换为图像

问题描述

我有一个快照功能,可以将我的 SwiftUI 视图转换为图像,但它似乎截断了我视图中的大部分内容。

如何调整 Snapshot 功能,以便它捕获我的 VStack 的所有内容并且不会切断任何内容?

预期结果:https ://i.stack.imgur.com/D1qsc.png

实际结果:https ://i.stack.imgur.com/PGmky.png

import SwiftUI

extension View {
    
    func theNewOfficialSnapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view
        
        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear
        
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        
        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
    
}


struct SnapshotView: View {
    var body: some View {
        
        Button(action: {
            
            let image = self.theNewOfficialSnapshot()
            print(image)
            
        }, label:{
            
            VStack{
            Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")
                .padding()
                .foregroundColor(.black)
                .background(Color.white)
                .mask(RoundedRectangle(cornerRadius: 30, style: .continuous))
                .shadow(color: Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)).opacity(0.3), radius: 10, x: 0, y:10)
                .padding()
                .frame(maxWidth: 300)
            
            }
        })
        
    }
}

struct SnapshotView_Previews: PreviewProvider {
    static var previews: some View {
        SnapshotView()
    }
}

标签: swiftfunctionswiftui

解决方案


添加.fixedSize(horizontal: false, vertical: true)到您的文本。


推荐阅读