I try to find the way to rotate the LinearGradient
object nested into e.g. Rectangle
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);
Now, I try to rotate this lg
object, for example for 45 degrees to the left, but without rotating the whole rect
. Is there any way to achieve that?
Advertisement
Answer
The first parameters that are given to the LinearGradient
constructor are the coordinates of the start- and end point of the gradient axis, respectively. This means that you can achieve a “rotated” gradient simply by passing in an appropriately rotated axis.
In the simplest form, for the example that 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 result in a gradient rotated by 45 degrees.
The fixed values here will affect the final appearance of the gradient, together with the other parameters. Referring to your example, this gradient with the same “wave length” as before (namely 100
), and start with the same color at the upper left corner (i.e. Color.BLACK
will be at coordinates (0,0)
).