【问题标题】:Converting SwiftUI View Into Image将 SwiftUI 视图转换为图像
【发布时间】:2021-10-04 03:30:40
【问题描述】:

我有一个 Snapshot 函数,可以将我的 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()
    }
}

【问题讨论】:

标签: swift function swiftui


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2023-04-06
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多