How to create new colors by blending two other SwiftUI colors
About 2 min
How to create new colors by blending two other SwiftUI colors 관련
SwiftUI by Example
Back to Home
How to create new colors by blending two other SwiftUI colors | SwiftUI by Example
How to create new colors by blending two other SwiftUI colors
Updated for Xcode 16
New in iOS 18
SwiftUI's Color
view has a mix(with:by:)
modifier that lets us blend two colors dynamically. This can be as simple as putting two colors together, like this:
Rectangle()
.fill(Color.red.mix(with: .indigo, by: 0.5))
However, you can also customize the colorspace. It's set to .perceptual
by default, meaning that humans perceive the colors to blend smoothly – it's not strictly accurate to exact color values, but it feels accurate to our eyes. We could also the .device
colorspace, which means the blending is more mathematically accurate as a value between 0 and 1:
Rectangle()
.fill(Color.red.mix(with: .indigo, by: 0.5, in: .device))
With this API, we can create a whole color picker and blender layout like this:
struct ContentView: View {
@State private var firstColor = Color.red
@State private var secondColor = Color.indigo
@State private var blendAmount = 0.5
var body: some View {
VStack {
ColorPicker("From", selection: $firstColor)
ColorPicker("To", selection: $secondColor)
Slider(value: $blendAmount)
Rectangle()
.fill(firstColor.mix(with: secondColor, by: blendAmount))
}
.padding()
}
}
Similar solutions…
How to show different images and other views in light or dark mode | SwiftUI by Example
How to show different images and other views in light or dark mode
How to layer views on top of each other using ZStack | SwiftUI by Example
How to layer views on top of each other using ZStack
How to hide the home indicator and other system UI | SwiftUI by Example
How to hide the home indicator and other system UI
How to hide the tab bar, navigation bar, or other toolbars | SwiftUI by Example
How to hide the tab bar, navigation bar, or other toolbars
How to use images and other views as backgrounds | SwiftUI by Example
How to use images and other views as backgrounds