Draw a semi ring - JavaFX

后端 未结 4 1777
梦毁少年i
梦毁少年i 2020-12-11 03:47

I would like to know how to draw a semi circle in JavaFX. I tried to use Shape and QuadCurve but I couldn\'t make a perfect semicircle.

Here is a picture of what I\'

4条回答
  •  無奈伤痛
    2020-12-11 04:32

    The picture you linked is actually a semi-ring. You can get it in JavaFX by drawing nested 2 arcs and some lines. But my preferred way is to use the Path.

    public class SemiDemo extends Application {
    
        @Override
        public void start(Stage primaryStage) {
    
            Group root = new Group();
            root.getChildren().add(drawSemiRing(120, 120, 100, 50, Color.LIGHTGREEN, Color.DARKGREEN));
            root.getChildren().add(drawSemiRing(350, 350, 200, 30, Color.LIGHTSKYBLUE, Color.DARKBLUE));
    
            Scene scene = new Scene(root, 300, 250);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        private Path drawSemiRing(double centerX, double centerY, double radius, double innerRadius, Color bgColor, Color strkColor) {
            Path path = new Path();
            path.setFill(bgColor);
            path.setStroke(strkColor);
            path.setFillRule(FillRule.EVEN_ODD);
    
            MoveTo moveTo = new MoveTo();
            moveTo.setX(centerX + innerRadius);
            moveTo.setY(centerY);
    
            ArcTo arcToInner = new ArcTo();
            arcToInner.setX(centerX - innerRadius);
            arcToInner.setY(centerY);
            arcToInner.setRadiusX(innerRadius);
            arcToInner.setRadiusY(innerRadius);
    
            MoveTo moveTo2 = new MoveTo();
            moveTo2.setX(centerX + innerRadius);
            moveTo2.setY(centerY);
    
            HLineTo hLineToRightLeg = new HLineTo();
            hLineToRightLeg.setX(centerX + radius);
    
            ArcTo arcTo = new ArcTo();
            arcTo.setX(centerX - radius);
            arcTo.setY(centerY);
            arcTo.setRadiusX(radius);
            arcTo.setRadiusY(radius);
    
            HLineTo hLineToLeftLeg = new HLineTo();
            hLineToLeftLeg.setX(centerX - innerRadius);
    
            path.getElements().add(moveTo);
            path.getElements().add(arcToInner);
            path.getElements().add(moveTo2);
            path.getElements().add(hLineToRightLeg);
            path.getElements().add(arcTo);
            path.getElements().add(hLineToLeftLeg);
    
            return path;
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    Refer to Shape API of JavaFX for more info about the shapes used in the code.
    Screenshot:

    enter image description here

提交回复
热议问题