簡體   English   中英

如何將圖像視圖置於錨窗格中心?

[英]How do I center an Image view in an anchor pane?

我正在使用場景構建器來創建我的GUI,並且當用戶選擇列表中的項目時,我正在顯示Image Image具有不同的大小,當Image小於其所在的窗格時,圖像顯示在窗格的左上角。 如何讓ImageView和/或Image顯示在Pane的中央?

我在整個javafx imageview和圖像API中看了一下,但是我沒有找到很多將ImageView集中在Pane 我也沒有在場景構建器中看到任何東西。 通常在場景構建器中,如果有一種方法可以使節點居中,則會有一個居中選項。

在任何類型的窗格中,現在可以在特定位置設置圖像對齊..為此您可以使用try HBox

當您將Image插入HBox ,最初顯示如下所示。

截圖

現在設置HBox的alignment屬性

截圖

現在將對齊更改為居中並查看輸出

截圖

我希望它為你工作

它也可以通過get圖像以編程方式在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);

在start方法中創建一個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);

在start方法中顯示primaryStage並執行其他代碼:

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);
    }
}

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM