【问题标题】:How can I get the center coordinates of a rectangle in javafx?如何在 javafx 中获取矩形的中心坐标?
【发布时间】:2019-01-01 10:27:26
【问题描述】:

有人知道如何在 javafx 中获取矩形的中心坐标吗? 有没有一种方法或算法,因为我想知道矩形旋转和移动时的中心位置。 我在网上找不到解决方案,所以我希望你们中的一个可以帮助我。

【问题讨论】:

    标签: javafx


    【解决方案1】:

    你可以这样计算一个矩形的中心:

    center.x = position.x + width / 2
    center.y = position.y + height / 2
    

    或者,如果您将矩形表示为 2 个点(两个对角),则必须使用以下公式:

    p0
    +-------+
    |       |
    |       |
    +-------+
           p1
    
    center.x = (p0.x + p1.x) / 2
    center.y = (p0.y + p1.y) / 2
    

    还有: 一个快速的谷歌产生How to find the Center Coordinate of Rectangle? 作为第一个结果......

    【讨论】:

    • 感谢您的回答,但我认为这种方法在矩形旋转时没用,不是吗?
    • 它非常适合旋转的矩形。想象一下通过你的矩形画一条对角线,然后标记这条线的中心。它也适用于缩放、平移和剪切的矩形。
    • 等等...你知道旋转点吗?还是那是你的问题?
    • 对不起,我是初学者。如何跟踪这些相反的点?据我所知,方法 .getTranslatex() / .getTranslateY() 总是占据矩形的最左边和最上角。
    • 请注意,您可能希望根据矩形的boundsInParent 属性计算中心;然后考虑所有转换。
    【解决方案2】:

    使用localToParent方法将矩形的中心转换为父坐标系。

    Rectangle 在局部坐标中的中心是

    x = rect.x + rect.width/2
    y = rect.y + rect.height/2
    

    示例

    @Override
    public void start(Stage primaryStage) throws Exception {
        Rectangle rect = new Rectangle(50, 50, 100, 100);
        Translate translate = new Translate();
        Rotate rotate = new Rotate(0, 0, 0);
        rect.getTransforms().addAll(translate, rotate);
        Circle circle = new Circle(5, Color.RED);
    
        AnimationTimer timer = new AnimationTimer() {
    
            @Override
            public void handle(long now) {
                double d = now / 5_000_000_000d;
                rotate.setAngle(d * 360);
                translate.setX((d % 2) * 300);
                translate.setY((d % 3) * 150);
    
                // set circle center to coordinates of rect's center
                Point2D center = rect.localToParent(rect.getX() + 0.5 * rect.getWidth(),
                        rect.getY() + 0.5 * rect.getHeight());
                circle.setCenterX(center.getX());
                circle.setCenterY(center.getY());
            }
    
        };
        Pane root = new Pane(rect, circle);
    
        timer.start();
    
        Scene scene = new Scene(root, 800, 800);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多