简体   繁体   中英

SwiftUI Gradient rendering incorrect colors on simulator

When running on the simulator, Gradient is rendering colors incorrectly. When running on a device, Gradient renders the colors correctly. How can I get Gradient to render colors correctly on the simulator so that I can capture accurate screenshots?

Simulator versus device:

模拟器 设备

Example View with Gradient :

struct GradientView: View {
    
    private static let backgroundGradientColors: [Color] = [.red, .blue]
    
    var body: some View {
        ZStack {
            GeometryReader { geometryReader in
                let gradient: Gradient = Gradient(colors: GradientView.backgroundGradientColors)
                RadialGradient(gradient: gradient,
                               center: .bottomTrailing,
                               startRadius: 0, endRadius: geometryReader.size.width)
                    .edgesIgnoringSafeArea(.all)
            }
        }
    }

}

This seems to happen if you use the built-in system colours. Once I changed to using asset catalog colours that have light and dark variants, they appeared correctly.

PS I had to delete the app from the sim each time I changed the colours to make them show correctly in the widget preview.

I just ran into this too. It obviously seems to be a bug in Xcode/Simulator, as everything looks correct on device.

This happens on my MacBook Pro 15" when it's attached to an external monitor, but interestingly everything appears totally normal in the SwiftUI preview and on Simulator when I run it on the normal built-in display.

So if you run into this and you're on a laptop with an external monitor, try unplugging and see if that helps.

If your gradient is drawn on top of a white background for the purposes of previewing in the simulator and Xcode canvas area, you can work around the bug by using a different blendMode (as mentioned here ):

/// Work around Xcode bug where SwiftUI gradients show up as green in the Simulator
let workAroundBlendMode: BlendMode = {
    #if targetEnvironment(simulator)
    return BlendMode.plusDarker
    #else
    return BlendMode.normal
    #endif
}()

RadialGradient(...)
    .blendMode(workAroundBlendMode)

The #if targetEnvironment(simulator) protects your release builds from the issues that come up when the background is not white, for example in Dark Mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM