如何在javaFX画布上绘制一些正确的圆心?

时间:2017-01-19 16:11:12

标签: canvas javafx pixels points

我在画布右侧中心创建了笔画圈(d = 26)(300x300) 默认字体大小为图形上下文的12pt(非PIXCEL)。 我想写上面创建的圆圈正中心有一位或两位数的数字。你能给我一些数学表达式来把这个文字写在圆圈的正中心。我也缺乏理解如何匹配12pt(POINTS)与像素。请有人帮帮我吗?

这是我的代码:

@Override
public void start(Stage primaryStage) {
    Pane root = new Pane();

    Scene scene = new Scene(root, 300, 300);
    primaryStage.setTitle("My Canvas");
    primaryStage.setScene(scene);
    primaryStage.show();

    Canvas cvs = new Canvas();
    cvs.setWidth(300);
    cvs.setHeight(300);
    cvs.setLayoutX(0);
    cvs.setLayoutY(0);
    root.getChildren().add(cvs);
    GraphicsContext gc = cvs.getGraphicsContext2D();

    gc.setFill(Color.BLACK);
    gc.setStroke(Color.BLUE);
    gc.setLineWidth(2);

    // creating circle (diameter = 26) right center of the canvas(300 x 300)
    // So, x = (widthOfCanvas-diameter)/2 , y = ((widthOfCanvas-diameter)/2
    double d = 26.0d;
    double x = (cvs.getWidth() - d)/2;
    double y = (cvs.getHeight() - d)/2;
    gc.strokeOval(x, y, d, d);

    // default font size is 12pt (NOT PIXCEL)
    gc.fillText("26", 150, 150); // How can I set this text right center of the circle? Please give me som mathematical expression
    // I also don't know relationship betwwen pt and px
    // What can I do?
}

1 个答案:

答案 0 :(得分:0)

谢谢你们俩!我已按照以下方式实施您的意见!现在我可以在任何地方画圆圈的数字!

 @Override
 public void start(Stage primaryStage) {
        Pane root = new Pane();

        Scene scene = new Scene(root, 300, 300);
        primaryStage.setTitle("My Canvas");
        primaryStage.setScene(scene);
        primaryStage.show();

        Canvas cvs = new Canvas();
        cvs.setWidth(300);
        cvs.setHeight(300);
        cvs.setLayoutX(0);
        cvs.setLayoutY(0);
        root.getChildren().add(cvs);

        GraphicsContext gc = cvs.getGraphicsContext2D();
        double x = (cvs.getWidth() - 26)/2;
        double y = (cvs.getHeight() - 26)/2;
        gc.drawImage(createCircledNumber(7), x, y);

        gc.drawImage(createCircledNumber(35), 50, 50);
        gc.drawImage(createCircledNumber(75), 70, 105);
    }

    private WritableImage createCircledNumber(int number) {
        //createCircledNumber() method always returns 26px X 26px sized image
        StackPane sPane = new StackPane();
        sPane.setPrefSize(26, 26);        

        Circle c = new Circle(26/2.0);
        c.setStroke(Color.BLACK);
        c.setFill(Color.WHITE);
        c.setStrokeWidth(3);
        sPane.getChildren().add(c);

        Text txtNum = new Text(number+"");
        sPane.getChildren().add(txtNum);
        SnapshotParameters parameters = new SnapshotParameters();
        parameters.setFill(Color.TRANSPARENT);
        return sPane.snapshot(parameters, null);
    }