How to get middle color between two UIColors in iOS

If I give two colors

UIColor *color1 = [UIColor blackColor]; UIColor *color2 = [UIColor whiteColor]; 

I should get grayColor as a result, how can I achieve it?

+8
ios objective-c uicolor
source share
3 answers

A direct way to find β€œbetween them” is to average four components, for example:

 UIColor *color1 = [UIColor blackColor]; UIColor *color2 = [UIColor whiteColor]; CGFloat r1, r2, g1, g2, b1, b2, a1, a2; [color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1]; [color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2]; UIColor *avg = [UIColor colorWithRed:(r1+r2)/2.0f green:(g1+g2)/2.0f blue:(b1+b2)/2.0f alpha:(a1+a2)/2.0f]; 

Note that this creates an RGBA midpoint color space, which is just one of many possible color spaces. Averaging components in other color spaces will produce a different result.

+13
source share

Answer in Swift 4+

 func blend(colors: [UIColor]) -> UIColor { let componentsSum = colors.reduce((red: CGFloat(0), green: CGFloat(0), blue: CGFloat(0))) { (temp, color) in guard let components = color.cgColor.components else { return temp } return (temp.0 + components[0], temp.1 + components[1], temp.2 + components[2]) } let components = (red: componentsSum.red / CGFloat(colors.count) , green: componentsSum.green / CGFloat(colors.count), blue: componentsSum.blue / CGFloat(colors.count)) return UIColor(red: components.red, green: components.green, blue: components.blue, alpha: 1) } 

It mixes as many colors as you would like

+3
source share

Here is a Swift implementation that is safe to use. Works with colors in different color spaces, but mixes with RGBA:

 func + (left: UIColor, right: UIColor) -> UIColor { var (r1, g1, b1, a1) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)) var (r2, g2, b2, a2) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)) left.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) right.getRed(&r2, green: &g2, blue: &b2, alpha: &a2) return UIColor(red: (r1 + r2)/2, green: (g1 + g2)/2, blue: (b1 + b2)/2, alpha: (a1 + a2)/2) } 

Using:

  view.backgroundColor = .red + .white 

Old answer:

 extension UIColor { func blended(with color: UIColor) -> UIColor? { guard cgColor.colorSpace == color.cgColor.colorSpace else { return nil } return UIColor(cgColor: CGColor(colorSpace: cgColor.colorSpace!, components: zip(cgColor.components!, color.cgColor.components!).map { ($0 + $1) / 2 } )!) } } 

But it only works with colors of the same color space, otherwise it will return zero. Here is a usage example:

 let white = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) view.backgroundColor = UIColor.red.blended(with: white) 
0
source share

All Articles