在 ImageView 中将图像居中 [英] Centering an image in an ImageView

查看:39
本文介绍了在 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 :

有没有办法做到这一点?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆