Skip to content
Advertisement

JavaFX Circle Linear Gradient Fill by Percentage

I just want to make an indicator for customer how much he/she used his/hers data/sms/voice using two circles and linear-gradient, but some values are not behaving as wanted. How can I make them behave same as in the image on the left?

enter image description here

This is the code I am using to create the gradient:

private void createCircleBar(int x, int y, int usedAmount, int remainingAmount) {
    int totalAmount = usedAmount + remainingAmount;
    int percentage = 100*usedAmount/totalAmount;
    Circle outerCircle = new Circle(x,y,50);
    LinearGradient g = LinearGradient.valueOf("from 0.0% 100.0% to 0.0% 0.0% rgb(14,170,0) 0.0%, rgb(14,170,0) "+(100-percentage)+"%, rgb(148,0,0) "+percentage+"%,rgb(148,0,0) 100.0%");
    outerCircle.setFill(g);
    anchor.getChildren().add(outerCircle);
    Circle innerCircle = new Circle(x,y,39);
    innerCircle.setFill(Color.WHITE);
    anchor.getChildren().add(innerCircle);
}

Advertisement

Answer

I think what you are looking to do is to have the red color rgb(148,0,0) from the top, extending down an amount determined by percentage, followed by the green color rgb(14, 170, 0) from that point to the bottom, with no actual color gradient in between the two colors.

A LinearGradient will interpolate the colors between any “color stops” you specify. So to create a hard change between two colors, you need two color stops at the same position, with one color changing to the other.

The following gives you what I think you are looking for:

LinearGradient g = LinearGradient.valueOf(
    "from 0.0% 0.0% to 0.0% 100.0% "+    // from top to bottom
    "rgb(148, 0, 0) 0%, "+               // red at the top
    "rgb(148, 0, 0) "+percentage+"%, "+  // red at percentage
    "rgb(14, 147, 0) "+percentage+"%, "+ // green at percentage
    "rgb(14, 147, 0) 100%"               // green at the bottom
);

Note you can literally use "from top to bottom " instead of "from 0% 0% to 0% 100% ".

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement