简体   繁体   English

为什么 JavaFX 会自动调整图像大小?

[英]why does JavaFX automatically resize images?

I have a 200x200 image.我有一个 200x200 的图像。

在此处输入图像描述

I load the above image into an ImageView but when I run the JavaFX application, the image appears larger.我将上面的图像加载到 ImageView 但是当我运行 JavaFX 应用程序时,图像看起来更大。 I took a screen capture and opened it in Paint.NET to confirm.我截屏并在 Paint.NET 中打开以确认。

在此处输入图像描述

Why is the image now 348x348?为什么现在的图像是 348x348? I tried everything I could think of to restrain the width and height to 200x200 (sample code below).我尝试了所有我能想到的将宽度和高度限制为 200x200(下面的示例代码)。 This Images automatically resized post is the closest thing I could find relating to my question but I am not developing for Android.这个自动调整大小的图片是我能找到的与我的问题最接近的东西,但我不是为 Android 开发的。

public class ImageTest extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Pane pane = new Pane();
        pane.setPrefHeight(200);
        pane.setPrefWidth(200);
        pane.setMaxHeight(200);
        pane.setMaxWidth(200);

        Image image = new Image(getClass().getClassLoader().getResourceAsStream("images/red square.png"));
        ImageView imageView = new ImageView( image );
        imageView.setImage(image);
        imageView.setFitHeight(200);
        imageView.setFitWidth(200);
        imageView.setPreserveRatio(true);
        imageView.setSmooth(false);
        pane.getChildren().add(imageView);

        Scene scene = new Scene( pane, 200, 200 );
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

With Image in loading加载中的图像

You can try loading the image with a predefined size.您可以尝试加载具有预定义大小的图像。 By default, it will not preserve the width:height ratio: you can make it do so with默认情况下,它不会保留width:height比:您可以使用

Image image = new Image("images/red square.png", 200, 200, true, false);

you can see information about that builder in javadocs您可以在javadocs中查看有关该构建器的信息


with image view use:使用图像视图

ImageView imageView = new ImageView("images/red square.png");
imageView.setPreserveRatio(true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM