Home > Blockchain >  How to mix two colors in SwitUI?
How to mix two colors in SwitUI?

Time:07-22

I want to mix two colors in SwiftUI code. For eg: Green and Black with opacity 20%. The final color should be a mix these two colors. Is there any method other than using ZStack to achieve the same?

CodePudding user response:

Since you are working in iOS, you can take advantage of the fact that a SwiftUI Color can be created from a UIColor.

Using UIColor.blend from this answer you can create a blend of 2 UIColors by specifying the colors and the intensity (0.0 ... 1.0) for each. For example, to create a foreground color for Text that is 80% UIColor.green and 20% UIColor.black:

struct ContentView: View {
    var body: some View {
        Text("Hello World!")
            .foregroundColor(Color(UIColor.blend(color1: .green, intensity1: 0.8, color2: .black, intensity2: 0.2)))
    }
}

Note: Just include the UIColor extension in any file in your project. It is a good practice to give extensions their own file(s), but you can include it in the same file as your View if you want.

  • Related