如何在锚窗格中居中图像视图?
-
21-12-2019 - |
题
我正在使用场景生成器来创建我的GUI,我正在显示 Image
s作为用户选择列表中的项目。该 Image
s是不同的大小,当一个 Image
这比它所在的窗格小,图像显示在窗格的左上角。我该如何获得 ImageView
和/或 Image
要显示在中心的 Pane
?
我已经查看了整个javafx imageview和image Api,但我没有找到太多关于居中的内容 ImageView
在一个 Pane
.我也没有在scene builder中看到任何东西。通常在场景构建器中,如果有办法使节点居中,则会有一个用于居中的选项。
解决方案
在任何类型的窗格中,现在都可以在特定位置设置图像对齐。.为此,您可以使用try HBox
当你插入一个 Image
进入 HBox
, ,最初如下所示。
现在设置对齐属性的 HBox
现在将对齐方式更改为中心并查看输出
我希望它对你的工作
也可以在 Pane
通过获取图像
试试这个
AnchorPane anchorPane = new AnchorPane();
Image img = new Image(getClass().getResourceAsStream("Edit-Male-User-icon.png"));
ImageView imageView = new ImageView(img);
anch.getChildren().add(imageView );
ImageView app = (ImageView) (Node) anchorPane.getChildren().get(0);
app.setX(100);
app.setY(100);
其他提示
创建一个 Group
和场景在你的开始方法:
Group root = new Group();
Scene scene = new Scene(root, 551, 400, Color.BLACK);
primaryStage.setScene(scene);
创建一个 ImageView
并设置以下属性:
ImageView imageView = new ImageView();
// set aspect ratio
imageView.setPreserveRatio(true);
// resize based on the scene
imageView.fitWidthProperty().bind(scene.widthProperty());
imageView.fitHeightProperty().bind(scene.heightProperty());
创建一个 StackPane
(至少这是我使用的)并绑定您的属性:
StackPane stack = new StackPane();
stack.getChildren().add(imageView);
stack.translateXProperty()
.bind(scene.widthProperty().subtract(stack.widthProperty())
.divide(2));
stack.translateYProperty()
.bind(scene.heightProperty().subtract(stack.heightProperty())
.divide(2));
将此堆栈添加到根元素:
root.getChildren().add(stack);
展览 primaryStage
并在您的start方法中执行其他代码:
primaryStage.show();
使小图像动态居中的简单方法 :
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class CenterInStage extends Application {
private final String TITLE = "Center in Stage";
private final double WIDTH = 350;
private final double HEIGHT = 250;
private final String IMAGE_PATH =
"http://icons.iconarchive.com/icons/iconka/meow-2/64/cat-rascal-icon.png";
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle(TITLE);
Image image = new Image(IMAGE_PATH);
ImageView imageView = new ImageView(image);
imageView.setPreserveRatio(true);
StackPane pane = new StackPane();
pane.getChildren().add(imageView);
StackPane.setAlignment(imageView, Pos.CENTER);
Scene scene = new Scene(pane, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
不隶属于 StackOverflow