【问题标题】:JavaFX How to crop image once for multiple aspect ratiosJavaFX如何为多个纵横比裁剪图像一次
【发布时间】:2019-02-14 16:02:04
【问题描述】:

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

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

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

【问题讨论】:

  • 看来你可以使用两张图片。一个用于瓷砖,另一个用于背景。您可以使用一些照片编辑程序编辑的背景。

标签: image javafx


【解决方案1】:

对于背景图片,您可以简单地指定图片应覆盖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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多