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; }
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With