Search code examples
javafxgradientshapescircular-dependencyintersect

JavaFX circular radial gradial radient in half circle


I need to add a circular radial gradient to a subtracted circle. I have been trying but I cannot get a circular gradient.

Circular radial gradient trial

1: Whole circle 2: Radial gradient in whole circle 3: Subtracted circle 4: Circular radial gradient trial in subtracted circle (not what I want) 5: Circular radial gradient in subtracted circle. This is what I want to obtain.

Once I get the subtracted circle (3), I apply the radial gradient but I get (4) instead of (5).

int x = 0.5;
int y = 0.5;

RadialGradient gradientCut = new RadialGradient(0, 0, x, y, 1, true, CycleMethod.NO_CYCLE, new 
Stop[] {
            new Stop(0, Color.ORANGE),
            new Stop(0.2, Color.YELLOW),
            new Stop(0.5, Color.TRANSPARENT)
});

Rectangle rect = new Rectangle(0, 0, 1000, 75);

Shape cutCircleGradient = Shape.intersect(circleGradientCut, rect);
cutCircleGradient.setFill(gradientCut);

I also tried changing values x and y but I'm not getting what I want.


Solution

  • Use clip to slice your circle:

    double x = 0.5;
    double y = 0.5;
    
    RadialGradient gradientCut = new RadialGradient(0, 0, x, y, 1, true, CycleMethod.NO_CYCLE, new
            Stop[]{
            new Stop(0, Color.ORANGE),
            new Stop(0.2, Color.YELLOW),
            new Stop(0.5, Color.TRANSPARENT)
    });
    double radius = 50.0;
    Circle c = new Circle(radius, gradientCut);
    var clip = new Rectangle(radius * 2, radius);
    clip.setTranslateX(-radius);
    clip.setTranslateY(-65);
    //clip.setTranslateY(-50);  --> half circle
    c.setClip(clip);