Skip to content

Instantly share code, notes, and snippets.

@otmb
Created September 15, 2023 13:37
Show Gist options
  • Save otmb/d6d22895a3c0f925dc2fed1da689f326 to your computer and use it in GitHub Desktop.
Save otmb/d6d22895a3c0f925dc2fed1da689f326 to your computer and use it in GitHub Desktop.
Create Image of SwiftUI layouts
import SwiftUI
import Charts
struct CreateImageView: View {
@State var uiImage: UIImage?
var body: some View {
VStack {
if let uiImage = uiImage {
Image(uiImage: uiImage)
}
}
.onAppear{
do {
let image = try createImage(AnyView(Page1()))
uiImage = image
} catch {
print(error.localizedDescription)
}
}
}
struct Page1: View {
let age = 22.0
var body: some View {
NavigationStack {
VStack {
List {
Grid(alignment: .leading){
GridRow {
Text("Name")
Text("Age")
}
.frame(width: 80)
Divider()
.gridCellUnsizedAxes(.horizontal)
GridRow {
Text("mbotsu")
Text(String(format: "%d", Int(age)))
}
.frame(width: 80)
}
}
.frame(width: 200, height: 120, alignment: .center)
.scrollContentBackground(.hidden)
.shadow(radius: 1)
Chart {
BarMark(
xStart: .value("", 20),
xEnd: .value("", 30)
)
.foregroundStyle(.blue)
.cornerRadius(10)
BarMark(
xStart: .value("", age - 0.5),
xEnd: .value("", age + 0.5)
)
.foregroundStyle(.cyan)
PointMark(
x: .value("", age)
)
.annotation(position: .overlay){
Image(systemName: "checkmark.seal")
.imageScale(.large)
.symbolRenderingMode(.palette)
.foregroundStyle(.black, .yellow)
.symbolVariant(.fill)
}
.foregroundStyle(.green)
}
.chartYAxis {
AxisMarks{}
}
.chartXAxis {
AxisMarks(preset: .aligned){
AxisValueLabel().font(.body)
}
}
.chartXScale(domain: 20...30)
.frame(width: 300, height: 100)
Spacer()
}
.navigationTitle("hoge")
}
}
}
}
func createImage(_ view: AnyView,
width:CGFloat=595.2,
height:CGFloat=841.8) throws -> UIImage {
let rect = CGRect(x: 0, y: 0, width: width, height: height)
guard let rootVC = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?
.windows.first?.rootViewController else {
throw NSError(domain: "rootViewController NotFound", code: -1)
}
let size = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIGraphicsBeginImageContext(size)
guard let context = UIGraphicsGetCurrentContext() else {
throw NSError(domain: "Context failed", code: -1)
}
let vc = UIHostingController(rootView: view)
vc.view.frame = rect
rootVC.addChild(vc)
rootVC.view.insertSubview(vc.view, at: 0)
context.clear(rect)
rootVC.view.layer.render(in: context)
vc.removeFromParent()
vc.view.removeFromSuperview()
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
throw NSError(domain: "Image context failed", code: -1)
}
UIGraphicsEndImageContext()
return image
}
struct CreateImageView_Previews: PreviewProvider {
static var previews: some View {
CreateImageView()
}
}
@otmb
Copy link
Author

otmb commented Sep 15, 2023

Preview Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment