Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

ios - Calculate the color at a given point on a gradient between two colors?

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: Example
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', and 1.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...