How to rotate the LinearGradient in a given Shape?

落花浮王杯 提交于 2019-12-22 05:13:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/25934678/how-to-rotate-the-lineargradient-in-a-given-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!