Render a SwiftUI view into an image on Dark mode not work

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?

You are not employing the color scheme on Text("Text"), are you?

Employ the color scheme inside the snapView guy.

    @ViewBuilder
    func snapView() -> some View {
        VStack {
            Text("Text")
                .background(colorScheme == .light ? .yellow : .brown)
            Text("Test2")
                .background(.green)
            snap
            snapEx()
        }
    }

Seems like ImageRenderer doesn't respect colorScheme. Did you find a solution for it?

For those wondering, I was able to fix something similar using a hacky solution by applying this modifier to the view I wanted to render:

.environment(\.colorScheme, colorScheme == .light ? .light : .dark)

@Environment(\.colorScheme) private var colorScheme.

Render a SwiftUI view into an image on Dark mode not work
 
 
Q