image - JavaFX如何为多个纵横比裁剪图像一次
问题描述
我在 JavaFX 中创建了一个桌面应用程序,它使用户能够搜索不同类别的人。有一个屏幕将每个类别显示为带有图像的图块(纵横比 1:1)。当您单击一个图块时,它会打开另一个页面,该图块中的图像现在应该显示为背景图像(纵横比 16:9)。图像由管理员用户选择,因此必须裁剪,因为它可能太大、纵横比错误等。
我想知道如何设置一种简单的方法来使管理员用户能够选择他想要的图片,而不必裁剪图像两次(一次为 1:1,一次为 16:9)。我考虑只裁剪为 1:1,然后显示为 16:9 只是缩放图片,但如果分辨率不够高,这会导致质量不佳。
对于裁剪,我参考了 Roland 的这篇文章: How to make a Javafx Image Crop App
解决方案
对于背景图像,您可以简单地指定图像应覆盖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();
}
推荐阅读
- javascript - 如何从外部网络应用程序在 Magento 中为特定商店生成折扣券?
- autohotkey - 如何在一系列输入后发送一个加法序列?
- sonarqube - Sonar Portfolio 未显示已配置的项目,消息组合没有项目,或关联项目都没有代码行
- pandas - 对于数组中的所有元素,将布尔值转换为零或一
- java - Java 中的每个类和包在 Android 中是否也可用?
- c++ - std::initializer_list 什么时候可以轻松构造?
- apache-kafka - Kafka - 阅读一包消息
- java - 从 BaseAdapter 的 getView 中获取方法中的值
- react-native - React Native Linking 'openUrl':如何选择默认浏览器?
- ubuntu - 导入的虚拟机生成 IP 失败