Draw linear gradient at a certain angle

426 Views Asked by At

I'm trying to draw linear gradients with libpixman using the pixman_image_create_linear_gradient() function. It works fine for drawing gradients that run from left to right and from top to bottom but I don't see how I can draw gradients at a specific angle (0-360 degrees) like they're possible in CSS. For example, a linear gradient that is rotated by 45 degrees.

I think one has to use the arguments p1 and p2 for this because they define the gradient direction but there is no documentation at all and I can't really figure out how to use these two parameters to rotate the gradient.

For vertical gradients I simply set them to

p1.x = 0; p1.y = 0;
p2.x = 0; p2.y = height - 1;

And for horizontal gradients I use

p1.x = 0; p1.y = 0;
p2.x = width - 1; p2.y = 0;

But which values should I use for arbitrary rotation? Simply applying a 2D rotation matrix to the points doesn't look right, e.g. when drawing a gradient that is 640x480 and rotating this by 45 degrees I end up with the points

p1.x = 81; p1.y = 560;
p2.x = 559; p2.y = 559;

which draws the gradient in the right direction but there are about 80 pixels of blank space on either side of the gradient so I must be doing something wrong.

Could anybody tell me how to get this right?

Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

I guess that Pixman implements linear gradients in the same way that Cairo does, given that Cairo's image backend uses Pixman, so look at some docs for Cairo. For example, in http://www.cairographics.org/tutorial/ in the section "Drawing with Cairo", subsection "Preparing and Selecting a Source" there is an explanation of linear gradients.

For your 45 degree rotation, I would try the following (one point in the top left corner, the other one in the bottom right one):

p1.x = 0; p1.y = 0;
p2.x = width - 1; p2.y = height - 1;

P.S.: No, I do not know how gradients with an angle are specified in CSS.