skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Here’s a solution without using UIColor. It’s based on the blend extension in @vacawama’s answer.

    import SwiftUI
    
    extension Color {
        static func blend(color1: Color, intensity1: CGFloat = 0.5, color2: Color, intensity2: CGFloat = 0.5) -> Color {
            let total = intensity1 + intensity2
            
            let normalisedIntensity1 = intensity1/total
            let normalisedIntensity2 = intensity2/total
            
            guard normalisedIntensity1 > 0 else { return color2 }
            guard normalisedIntensity2 > 0 else { return color1 }
            
            let color1Components = color1.cg.components!
            let color2Components = color2.cg.components!
            
            let (r1, g1, b1, a1): (CGFloat, CGFloat, CGFloat, CGFloat) = (color1Components[0], color1Components[1], color1Components[2], color1Components[3])
            let (r2, g2, b2, a2): (CGFloat, CGFloat, CGFloat, CGFloat) = (color2Components[0], color2Components[1], color2Components[2], color2Components[3])
    
            return Color(red: normalisedIntensity1*r1 + normalisedIntensity2*r2,
                         green: normalisedIntensity1*g1 + normalisedIntensity2*g2,
                         blue: normalisedIntensity1*b1 + normalisedIntensity2*b2,
                         opacity: normalisedIntensity1*a1 + normalisedIntensity2*a2)
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search