[英]JavaFX center a Ractangle within a Pane
我有以下代碼,它制作了一個基本的窗格,里面有一個矩形:
public class Canvas extends Pane{
public Canvas() {
Rectangle rect = new Rectangle(50,50, Color.GOLD);
this.setBackground(new Background(new BackgroundFill(Color.INDIANRED,new CornerRadii(0),new Insets(0))));
this.setPrefSize(200, 200);
rect.setX((this.getMaxWidth()/2) + (rect.getWidth()));
rect.setY((this.getMaxHeight()/2) + (rect.getHeight()));
this.getChildren().add(rect);
}
我已經嘗試了一些方法來讓三角形的中心位於窗格的中心(上面代碼中的一個示例),但是因為在 JavaFX 中,矩形的 X 和 Y 坐標代表左上角,它使它變得更多很難在我的窗格中居中。 我的數學很差,不知道實現這一目標的正確公式。 如何讓矩形的中心與窗格的中心對齊? 不使用 Stackpane 等...
您希望將 Rectangle 的中點與 Pane 的中點對齊。
您必須找到窗格的中點(x 和 y)和矩形(x 和 y)。
// Find the midpoint of the Pane.
// x midpoint
float xPaneMidpoint = pane.width / 2
// y midpoint
float yPaneMidpoint = pane.height/ 2
然后將矩形移動到窗格中點的 position,然后將其偏移其大小的一半
// Take the midpoint of the pane, and move the rectangle to that point.
// Then offset it by half its width/height
rectangle.setX( xPaneMidpoint - (rectangle.width / 2));
rectangle.setX( yPaneMidpoint - (rectangle.height/ 2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.