Calculate the color at a given point on a gradient between two colors?
You simply linearly interpolate the red, the green, and the blue channels like this:
double resultRed = color1.red + percent * (color2.red - color1.red);
double resultGreen = color1.green + percent * (color2.green - color1.green);
double resultBlue = color1.blue + percent * (color2.blue - color1.blue);
where percent
is a value between 0 and 1 (location
in your first method prototype).
Related videos on Youtube
blabus
Updated on July 09, 2022Comments
-
blabus almost 2 years
So this is essentially the method I would like to write (in Objective-C/Cocoa, using
UIColors
, but I'm really just interested in the underlying math):+ (UIColor *)colorBetweenColor:(UIColor *)startColor andColor:(UIColor *)endColor atLocation:(CGFloat)location;
So as an example, say I have two colors, pure red and pure blue. Given a linear gradient between the two, I want to calculate the color that's at, say, the 33% mark on that gradient:
So if I were to call my method like so:UIColor *resultingColor = [UIColor colorBetweenColor:[UIColor redColor] andColor:[UIColor blueColor] atLocation:0.33f];
I would get the resulting color at 'B', and similarly, passing
0.0f
as the location would return color 'A', and1.0f
would return color 'C'.So basically my question is, how would I go about mixing the RGB values of two colors and determining the color at a certain 'location' between them?
-
andreamazz about 10 yearsYou might want to take a look at this answer
-
-
user1118321 over 9 years@LudovicLandry Can you elaborate? You can linearly interpolate colors in any color space, though the results may not always be pleasing or what you expect. (In fact, even in RGB, you often pass through gray which is sometimes not desired.) In what way does the above not work for which color spaces?
-
Ludovic Landry over 9 yearsFor example, this will not work on [UIColor whiteColor] as that is not in RGB. See stackoverflow.com/questions/4700168/…
-
user1118321 over 9 years@LudovicLandry - Ah, I see what you mean. Yes, you would have to convert named colors to some other color space (RGB, HSV, CMYK, whatever). But once they're in a color space that you can do math on, linearly interpolating will work just fine.
-
Henrik over 7 yearsRGB is not like a circle, it is a cube. Spaces like HSV or HSB form a circle with the hue in degrees or radians.
-
Gregorio Freidin over 2 yearsThanks man. I feel dumb for not realizing this. Thanks a ton.