swift - 将 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()
}
}
解决方案
添加.fixedSize(horizontal: false, vertical: true)
到您的文本。
推荐阅读
- react-native - 带有 React Native 的 TypeORM
- python - Pandas DataFrame 索引,选择具有 NaN 值的特定列的行
- javascript - 自 Spectre 和 Meltdown 以来如何在 JavaScript 中获得微秒计时
- windows - PYTHONPATH 在 Windows 上被 python3 忽略
- php - Ubuntu 18.04 上的 Apache 2 + Xdebug + PHP 7.2 不工作
- javascript - 无法访问函数之外的变量,即使它是全局的
- .net - 自定义 API 动态验证不同的 SharePoint 租户
- regex - php regex pregmatch 删除字符之间的零
- r - 函数默认给定为向量
- r - R i386 3.1.0版本vegan包安装错误