在ImageView中居中图像 [英] Centering an image in an ImageView
问题描述
我目前正在尝试使用JavaFX将图像置于ImageView中心。
I am currently trying to center an image in an ImageView using JavaFX.
所以我在视图中加载图像:
So I load the image in the view :
Image img = new Image("...");
imageView.setImage(img);
让我们假设图像很大(2000x3000)而不是ImageView(400x100)
and let's suppose the image is huge (2000x3000) and not the ImageView (400x100)
渲染的图像将在左侧对齐,我想放在ImageView的中心:
The rendered image will be aligned on the left, and I would like to put in the center of the ImageView :
< a href =https://i.stack.imgur.com/nKIWz.jpg =nofollow noreferrer>
无论如何都要执行此操作?
Is there anyway to perform that ?
推荐答案
因此,经过几天的计算,我找到了一个很好的方法来做到这一点。
So, after days of calculation, I managed to find a good way to do it.
我在这里发布,以防有人想要实现它。
I post it here in case of someone would like to achieve it.
我创建了一个只需要访问imageView的方法:
I created a method that only needs access to the imageView :
public void centerImage() {
Image img = imageView.getImage();
if (img != null) {
double w = 0;
double h = 0;
double ratioX = imageView.getFitWidth() / img.getWidth();
double ratioY = imageView.getFitHeight() / img.getHeight();
double reducCoeff = 0;
if(ratioX >= ratioY) {
reducCoeff = ratioY;
} else {
reducCoeff = ratioX;
}
w = img.getWidth() * reducCoeff;
h = img.getHeight() * reducCoeff;
imageView.setX((imageView.getFitWidth() - w) / 2);
imageView.setY((imageView.getFitHeight() - h) / 2);
}
}
这篇关于在ImageView中居中图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!