gpt4 book ai didi

javaFX-什么是 getBoundsInLocal() 、getBoundsInParent() 方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:31 25 4
gpt4 key购买 nike

图像(这里是名为hero 的节点)根据键盘上按下的KEY 移动。但是使用了一个名为 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 width/heightimageImageView 一起使用

关于javaFX-什么是 getBoundsInLocal() 、getBoundsInParent() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com