This is my test code.
import SwiftUI
extension View {
@MainActor func render(scale: CGFloat) -> UIImage? {
let renderer = ImageRenderer(content: self)
renderer.scale = scale
return renderer.uiImage
}
}
struct ContentView: View {
@Environment(\.colorScheme) private var colorScheme
@State private var snapImg: UIImage = UIImage()
var snap: some View {
Text("I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.foregroundStyle(colorScheme == .dark ? .red : .green)
}
@ViewBuilder
func snapEx() -> some View {
VStack {
Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.foregroundStyle(colorScheme == .dark ? .red : .green)
Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.background(.pink)
Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.background(.purple)
Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.foregroundStyle(colorScheme == .dark ? .red : .green)
Text("@ViewBuilder I'm now is \(colorScheme == .dark ? "DARK" : "LIGHT") Mode!")
.foregroundStyle(colorScheme == .dark ? .red : .green)
}
}
@ViewBuilder
func snapView() -> some View {
VStack {
Text("Text")
Text("Test2")
.background(.green)
snap
snapEx()
}
}
var body: some View {
let snapView = snapView()
VStack {
snapView
Image(uiImage: snapImg)
Button("Snap") {
snapImg = snapView.render(scale: UIScreen.main.scale) ?? UIImage()
}
}
}
}
When using ImageRenderer, there are some problems with converting View to images. For example, Text cannot automatically modify the foreground color of Dark Mode.
This is just a simple test code, not just Text.
How should I solve it?