Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mid color between two UIColors in iOS

If i give two colors

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

I should get grayColor as result, how shall I achieve it?

like image 624
Sunil Rao Avatar asked Nov 04 '15 10:11

Sunil Rao


Video Answer


2 Answers

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 blends as many colors as you'd like

like image 106
Federico Zanetello Avatar answered Nov 16 '22 02:11

Federico Zanetello


A straightforward way of finding the "in between" is to average the four components, like this:

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 produces a midpoint RGBA color space, which is only one of many possible color spaces. Averaging components in other color spaces will lead to a different result.

like image 27
Sergey Kalinichenko Avatar answered Nov 16 '22 01:11

Sergey Kalinichenko