Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

graphics - How do I calculate a four colour gradient?

If I have four colours (A, B, C & D) on four corners of a square and I want to fill that square with a gradient that blends nicely between the four colours how would I calculate the colour of the point E?

The closer E is to any of the other points, the strong that colour should affect the result.

Any idea how to do that? Speed and simplicity is preferred to accuracy.

colours http://rabien.com/image/colours.png

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The best solution when a gradient is required between two colors, is to use the HSV representation (Hue Saturation Value).

If you have the HSV values for your two colors, you just make linear interpolation for H, S and V, and you have nice colors (interpolation in RGB space always lead to "bad" results).

You also find here the formulae to go from RGB to HSV and from HSV to RGB, respectively.

Now, for your problem with the four corner, you can make a linear combination of the four H/S/V values, weighted by the distance from E to that four points A,B,C and D.

EDIT: same method than tekBlues, but in HSV space (it is quite easy to test it in RGB and in HSV spaces. And you will see the differences. In HSV, you just turn around the chromatic cylinder, and this is why it gives nice result)

EDIT2: if you prefer "speed and simplicity", you may use a L1-norm, instead of a L2-norm (euclidian norm)

So, if a is the size of your square and the coordinate of your points are A(0,0), B(0,a), C(a,0), D(a,a), then the Hue of a point E(x,y) can be computed with:

Hue(E) = ( Hue(B)*y/a + Hue(A)*(1-y/a) ) * (x/a)  +  ( Hue(D)*y/a + Hue(C)*(1-y/a) ) * (1-x/a)

where Hue(A) is the Hue of point A, Hue(B) the Hue of B, etc...

You apply the same formulae for the Saturation and Value.

Once you have the Hue/Saturation/Value for your point E, you can transform it in RGB space.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...