问题描述
所以这基本上就是我想要编写的方法(在 Objective-C/Cocoa 中,使用 UIColors
,但我真的只是对基础数学感兴趣):
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;
举个例子,假设我有两种颜色,纯红色和纯蓝色.给定两者之间的线性渐变,我想计算该渐变上的 33% 标记处的颜色:
所以如果我像这样调用我的方法:
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];
我会在B"处得到结果颜色,类似地,通过 0.0f
作为位置将返回颜色A",而 1.0f
将返回颜色'C'.
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'.
所以基本上我的问题是,我将如何混合两种颜色的 RGB 值并确定它们之间某个位置"的颜色?
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?
推荐答案
您可以像这样简单地线性插值红色、绿色和蓝色通道:
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);
其中 percent
是 0 到 1 之间的值(location
在您的第一个方法原型中).
where percent
is a value between 0 and 1 (location
in your first method prototype).
这篇关于计算两种颜色之间渐变上给定点的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!