How do I rotate a linear gradient in a given shape?

I am trying to find a way to rotate an object LinearGradient

nested in eg. Rectangle

an object, say:

Rectangle rect = new Rectangle(0, 0, 200, 200);

LinearGradient lg = new LinearGradient(0, 0, 100, 0, false, CycleMethod.REPEAT, new Stop[] {
    new Stop(0, Color.BLACK);
    new Stop(0.5, Color.WHITE);
    new Stop(1, Color.BLACK);
});

rect.setFill(lg);

      

enter image description here

Now I am trying to rotate this object lg

, for example 45 degrees to the left, but without rotating everything rect

. Is there a way to achieve this?

+3


source to share


1 answer


The first parameters given to the constructor LinearGradient

are the coordinates of the start and end points of the gradient axis, respectively. This means that you can achieve a "rotated" gradient simply by traversing the appropriate rotation axis.

In its simplest form, for the example you described, you can use the following pattern:

double angleInRadians = Math.toRadians(45);
double length = 100; 

double endX = Math.cos(angleInRadians) * length;
double endY = Math.sin(angleInRadians) * length;

LinearGradient lg = new LinearGradient(0, 0, endX, endY, ...);

      



This will cause the gradient to rotate 45 degrees.

The fixed values ​​here affect the final appearance of the gradient along with other parameters. Referring to your example, this gradient is with the same "wavelength" as before (namely 100

) and starting with the same color in the upper left corner (ie Color.BLACK

will be in coordinates (0,0)

).

+9


source







All Articles