Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
blabus Avatar asked Mar 06 '14 07:03

blabus


People also ask

How do you find the gradient of a color?

Select the Gradient tool in the toolbar. In the selected artwork you'll see the gradient annotator, which shows the gradient slider and the color stops. Double-click a color stop on the artwork to edit the color, drag the color stops, click beneath the gradient slider to add new color stops, and more.

How many colors are allowed into a color gradient?

Color gradients, or color transitions, are defined as a gradual blending from one color to another. This blending can occur between colors of the same tone (from light blue to navy blue), colors of two different tones (from blue to yellow), or even between more than two colors (from blue to purple to red to orange).

What is the required number of colors to produce a gradient effect?

To create the most basic type of gradient, all you need is to specify two colors. These are called color stops. You must have at least two, but you can have as many as you want.

What is a gradient of color called?

A color gradient is also known as a color ramp or a color progression. In assigning colors to a set of values, a gradient is a continuous colormap, a type of color scheme.


1 Answers

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

like image 77
user1118321 Avatar answered Oct 13 '22 14:10

user1118321