Reputation: 18908
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)
}
}
}
}
Upvotes: 15
Views: 1703
Reputation: 3913
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.
Upvotes: 1
Reputation: 14838
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.
Upvotes: 1
Reputation: 362
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.
P.S. I had to delete the app from the sim each time I changed the colours to make them show correctly in the widget preview.
Upvotes: 2