简体   繁体   English

CGGradientCreateWithColors / CGContextDrawLinearGradient - 计算中间颜色组合的公式?

[英]CGGradientCreateWithColors / CGContextDrawLinearGradient - formula to calculate intermediate colour combinations?

Does anyone know the formula used by CGGradientCreateWithColors to calculate the intermediate colours at each point along the gradient?有谁知道 CGGradientCreateWithColors 用来计算渐变中每个点的中间颜色的公式? I want to reproduce the colour for a given point - eg with CGGradientCreateWithColors using only 2 colours set to locations = 0 and 1, what would be the colour on the gradient at point 0.2 or any other defined point between 0 and 1?我想重现给定点的颜色 - 例如,使用 CGGradientCreateWithColors 仅使用设置为位置 = 0 和 1 的 2 种颜色,点 0.2 或 0 和 1 之间的任何其他定义点的渐变颜色是什么? I use CGContextDrawLinearGradient to draw the background of one UIView with the full gradient, but I also want to colour a second UIView with the colour for a specific distance along the gradient, which would vary according to a value mapped to the 0..1 scale.我使用 CGContextDrawLinearGradient 绘制具有完整渐变的 UIView 的背景,但我还想使用沿渐变特定距离的颜色为第二个 UIView 着色,这将根据映射到 0..1 比例的值而变化.

Any suggestions how to get this blend of the two colours to match the colour at a fixed point along the CGGradient wouild be greatly appreciated.任何关于如何让这两种颜色混合以匹配沿 CGGradient 的固定点的颜色的任何建议都将不胜感激。 Thanks谢谢

Larme's formula does the trick for me, where the proportion of the second colour (colour at location 1.0 in CGGradientCreateWithColors) that you want expressed (ie the "distance" between colour at 0.0 and colour at 1.0) is P in the formula below. Larme 的公式对我有用,您想要表达的第二种颜色(CGGradientCreateWithColors 中位置 1.0 的颜色)的比例(即颜色 0.0 和颜色 1.0 之间的“距离”)在下面的公式中是 P。 The proportion of colour 0 expressed then becomes (1 - P).表示的颜色 0 的比例则变为 (1 - P)。 P is a value between 0..1, so (to state the obvious) 75% of colour 1 gives P = 0.75, and this means colour 0 has 25% expression (1 - 0.75). P 是一个介于 0..1 之间的值,因此(对于 state 很明显)75% 的颜色 1 给出 P = 0.75,这意味着颜色 0 有 25% 的表达式 (1 - 0.75)。

CGFloat P = 0.75; // any value between 0.0 .. 1.0
CGFloat b = 1 - P;
UIColor* col0 = [UIColor yellowColour]; // or whatever ...
UIColor* col1 = [UIColor redColor]; // or whatever ...
CGFloat R0,R1,G0,G1,B0,B1,A0,A1;
[col0 getRed:&R0 green:&G0 blue:&B0 alpha:&A0];
[col1 getRed:&R1 green:&G1 blue:&B1 alpha:&A1];
UIColor* blendedColour = [UIColor 
    colorWithRed: R1 * P + R0 * b 
    green:        G1 * P + G0 * b 
    blue:         B1 * P + B0 * b
    alpha:        A1 * P + A0 * b];
// P = 0.75 gives red-orange colour. P = 0.5 gives orange. etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM