Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIColor transition based on progress value

I have a ProgressBar to which I want to assign a customColor color and based on the progress fade to another color. Using the method below I get a dark rainbow effect color including reds and dark brown and dark green. The start color will be a light blue one and the destination color a light green.

-(UIColor *) makeCustomColorFromProgressValue:(float) progress{   UIColor *color;  // startColor Color - lightBlue float red = 0.53; float green = 0.82; float blue = 1;  //Destination Color - lightGreen float finalRed = 0.53; float finalGreen = 1; float finalBlue = 0.82;  float newRed = 80;//finalRed *255; float newGreen = (finalGreen *progress) *255; float newBlue = (finalBlue *progress) *255; color = Rgb2UIColor(newRed, newGreen, newBlue);    return color; } 
like image 769
snksnk Avatar asked Apr 04 '14 16:04

snksnk


2 Answers

You can do a "linear interpolation" between the colors:

CGFloat newRed   = (1.0 - progress) * red   + progress * finalRed; CGFloat newGreen = (1.0 - progress) * green + progress * finalGreen; CGFloat newBlue  = (1.0 - progress) * blue  + progress * finalBlue; UIColor *color = [UIColor colorWithRed:newRed green:newGreen blue:newBlue alpha:1.0]; 

This gives the initial color for progress == 0 and the final color for progress == 1.

like image 179
Martin R Avatar answered Oct 06 '22 14:10

Martin R


Swift version converted from the code from Jonathan Ellis

extension UIColor {     func interpolateRGBColorTo(_ end: UIColor, fraction: CGFloat) -> UIColor? {         let f = min(max(0, fraction), 1)          guard let c1 = self.cgColor.components, let c2 = end.cgColor.components else { return nil }          let r: CGFloat = CGFloat(c1[0] + (c2[0] - c1[0]) * f)         let g: CGFloat = CGFloat(c1[1] + (c2[1] - c1[1]) * f)         let b: CGFloat = CGFloat(c1[2] + (c2[2] - c1[2]) * f)         let a: CGFloat = CGFloat(c1[3] + (c2[3] - c1[3]) * f)          return UIColor(red: r, green: g, blue: b, alpha: a)     } }  let color1 = UIColor(red: 0.035, green: 0.216, blue: 0.933, alpha: 1.00) let color2 = UIColor(red: 0.933, green: 0.794, blue: 0.000, alpha: 1.00)  color1.interpolateRGBColorTo(color2, fraction:0.1) 

UIColor Interpolation

like image 45
Atika Avatar answered Oct 06 '22 13:10

Atika