如何缩放居中的BufferedImage,使其在调整JFrame大小时保持自己的纵横比



我有一个可调整大小的窗口,默认大小为1280x720,图像分辨率为1280x720。

如果在调整大小时保持默认的纵横比,它看起来很好。然而,如果用户的屏幕分辨率恰好为1900x1080,则图像比例会略有拉伸,如果用户有一台旧显示器(1024x768),则拉伸看起来很糟糕。

我想要的是在图像居中的情况下始终保持图像的16:9比例,并根据窗口的宽度/高度是否分别比默认图像长/短来缩放图像。

有没有办法在不牺牲性能的情况下做好这件事?

非常简单。

这是我的测试程序的结果。

java.awt.Dimension[width=1024,height=576]
java.awt.Dimension[width=1600,height=900]

您有原始的纵横比和新的纵横比。

您只需要得到宽度差和高度差的增量,然后使用较小的增量来重新计算新的纵横比。

这是测试代码。

package com.ggl.testing;
import java.awt.Dimension;
public class AspectRatio {
    public static void main(String[] args) {
        AspectRatio aspectRatio = new AspectRatio();
        Dimension aspect = new Dimension(1280, 720);
        System.out.println(aspectRatio.aspectRatio(aspect, new Dimension(1024,
                768)));
        System.out.println(aspectRatio.aspectRatio(aspect, new Dimension(1600,
                1000)));
    }
    public Dimension aspectRatio(Dimension aspect, Dimension newAspect) {
        double deltaWidth = (double) newAspect.width / aspect.width;
        double deltaHeight = (double) newAspect.height / aspect.height;
        double delta = Math.min(deltaWidth, deltaHeight);
        int width = (int) Math.round(aspect.width * delta);
        int height = (int) Math.round(aspect.height * delta);
        return new Dimension(width, height);
    }
}

最新更新