首页 > 解决方案 > JavaFX如何为多个纵横比裁剪图像一次

问题描述

我在 JavaFX 中创建了一个桌面应用程序,它使用户能够搜索不同类别的人。有一个屏幕将每个类别显示为带有图像的图块(纵横比 1:1)。当您单击一个图块时,它会打开另一个页面,该图块中的图像现在应该显示为背景图像(纵横比 16:9)。图像由管理员用户选择,因此必须裁剪,因为它可能太大、纵横比错误等。

我想知道如何设置一种简单的方法来使管理员用户能够选择他想要的图片,而不必裁剪图像两次(一次为 1:1,一次为 16:9)。我考虑只裁剪为 1:1,然后显示为 16:9 只是缩放图片,但如果分辨率不够高,这会导致质量不佳。

对于裁剪,我参考了 Roland 的这篇文章: How to make a Javafx Image Crop App

标签: imagejavafx

解决方案


对于背景图像,您可以简单地指定图像应覆盖Region.

ImageView允许您指定一个viewport允许您指定Image应显示的区域。如果相应地选择,这会为您进行裁剪。

为简单起见,以下代码使用相同的比率:

@Override
public void start(Stage primaryStage) {
    final Image image = new Image(URL);

    // size to use for both nodes
    double targetHeight = 400;
    double targetWidth = targetHeight * 16 / 9;

    ImageView imageView = new ImageView(image);
    imageView.setFitWidth(targetWidth);
    imageView.setFitHeight(targetHeight);

    // calculate viewport
    imageView.setViewport((image.getHeight() / targetHeight < image.getWidth() / targetWidth)
            ? new Rectangle2D(0, 0, image.getHeight() / targetHeight * targetWidth, image.getHeight())
            : new Rectangle2D(0, 0, image.getWidth(), image.getWidth() / targetWidth * targetHeight));

    Region backgroundRegion = new Region();
    backgroundRegion.setPrefSize(targetWidth, targetHeight);
    backgroundRegion.setBackground(new Background(
            new BackgroundImage(
                    image,
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundRepeat.NO_REPEAT,
                    BackgroundPosition.CENTER,
                    new BackgroundSize(0, 0, false, false, false, true) // cover
            )));

    HBox root = new HBox(imageView, backgroundRegion);
    root.setFillHeight(false);
    root.setPadding(new Insets(20));

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

推荐阅读