[英]javaFX- what is getBoundsInLocal() ,getBoundsInParent() method?
根據鍵盤中按下的KEY移動圖像(此處為名為hero
的節點)。 但是使用名為getBoundsInLocal()
的方法。 我無法真正理解這種方法的目的。 獲取圖像的寬度和高度是否有幫助?
private void moveHeroBy(int dx, int dy) {
if (dx == 0 && dy == 0) return;
final double cx = hero.getBoundsInLocal().getWidth() / 2;
final double cy = hero.getBoundsInLocal().getHeight() / 2;
double x = cx + hero.getLayoutX() + dx;
double y = cy + hero.getLayoutY() + dy;
moveHeroTo(x, y);
}
private void moveHeroTo(double x, double y) {
final double cx = hero.getBoundsInLocal().getWidth() / 2;
final double cy = hero.getBoundsInLocal().getHeight() / 2;
if (x - cx >= 0 &&
x + cx <= W &&
y - cy >= 0 &&
y + cy <= H) {
hero.relocate(x - cx, y - cy);
}
}
這種方法由AnimationTimer
以這種方式調用:
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
int dx = 0, dy = 0;
if (goNorth) dy -= 1;
if (goSouth) dy += 1;
if (goEast) dx += 1;
if (goWest) dx -= 1;
if (running) { dx *= 3; dy *= 3; }
moveHeroBy(dx, dy);
}
};
timer.start();
我找到了名為getBoundsInParent()的類似方法。 這兩種方法做了什么以及有什么區別?
getBoundsInLocal
在其自己的坐標系中返回Node
的邊界。 getBoundsInParent
根據轉換/ layoutX
/ layoutY
調整它們后返回邊界。 兩者都可用於確定尺寸,但您需要的尺寸取決於您使用的坐標系...
例
Rectangle rect = new Rectangle(100, 200);
rect.setLayoutX(11);
rect.setLayoutY(33);
rect.setScaleX(2);
Pane root = new Pane();
root.getChildren().add(rect);
System.out.println(rect.getBoundsInLocal());
System.out.println(rect.getBoundsInParent());
版畫
BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:100.0, height:200.0, depth:0.0, maxX:100.0, maxY:200.0, maxZ:0.0]
BoundingBox [minX:-39.0, minY:33.0, minZ:0.0, width:200.0, height:200.0, depth:0.0, maxX:161.0, maxY:233.0, maxZ:0.0]
對於未轉換的ImageView
您可以使用viewport
的大小確定大小,或者如果將此屬性設置為null
,則使用ImageView
使用的image
的width
/ height
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.