Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate the LinearGradient in a given Shape?

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);

enter image description here

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?

like image 882
bluevoxel Avatar asked Sep 19 '14 13:09

bluevoxel


People also ask

How do you rotate a gradient?

To rotate a gradient fill: To rotate a linear gradient, drag the round handle (Figure 4.49). Figure 4.49 As you drag the gradient's rotate handle with the gradient-transform tool, you spin the gradient around its center point.

What is linear gradient in SVG?

SVG provides two types of gradients. Linear Gradients − Represents linear transition of one color to another from one direction to another. Radial Gradients − Represents circular transition of one color to another from one direction to another.

Can SVG files have gradients?

SVG provides for two types of gradients: linear gradients and radial gradients. Once defined, gradients are then referenced using 'fill' or 'stroke' properties on a given graphics element to indicate that the given element shall be filled or stroked with the referenced gradient.


1 Answers

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)).

like image 168
Marco13 Avatar answered Oct 06 '22 12:10

Marco13