Wednesday, October 31, 2018

Another LinearGradient...

Aloha,

I was playing around with a JavaFX application for a customer and missed a functionality from the JavaFX LinearGradient. So you can define a linear gradient by defining a start and end point and fill it either proportional or not.
Well this works most of the time but if you have to create the linear gradient from code it sometimes could be useful if you simply could define an angle and a list of stops to define the gradient. So here is a little drawing that explains it a bit better:



In principle I would just need to extend the existing LinearGradient but unfortunately this is not possible :(
So I have to create a new class, in this case I named it LinearGradientD and this simply wraps a LinearGradient and takes an angle and a list of Stops as parameters.
So the main thing you have to do is to turn the angle in xy coordinates for the gradient and the code is really simple, so here it is:


private void init(final double angle, final List<Stop> stops) {
    this.angle = angle % 360;

    double angleRad = Math.toRadians(angle);
    double x        = Math.cos(angleRad);
    double y        = Math.sin(-angleRad);

    double x1 = x > 0 ? 0 : Math.abs(x);
    double y1 = y > 0 ? 0 : Math.abs(y);
    double x2 = x > 0 ? Math.abs(x) : 0;
    double y2 = y > 0 ? Math.abs(y) : 0;

    gradient = new LinearGradient(x1, y1, x2, y2, true, CycleMethod.NO_CYCLE, stops);
}

As you can see we simply calculate the xy values from the angle using some trigonometry and set the resulting xy coordinates in the wrapped LinearGradient object.
One advantage of using the angle to describe the gradient is that you can now also easily rotate the gradient as you can see in the following video:



Well I guess that's already it for today, nothing special but I thought it might be worth blogging about it.
Of course the code is available on github, so feel free to use it for whatever you need it.

So...keep coding... :)

No comments:

Post a Comment