gpt4 book ai didi

java - 根据屏幕分辨率调整大小,Java 应用程序

转载 作者:行者123 更新时间:2023-12-01 10:05:11 28 4
gpt4 key购买 nike

我即将准备好分发此应用程序。但是我仍然没有找到一种方法来使应用程序适合任何屏幕。事实上,我在 JLabels 中使用 pngs 文件作为背景和按钮(主要),我认为这是一个巨大的问题。我想要实现的是让 JFrame 及其组件可调整大小但保持比例,就像响应式网站一样!我计划用其他方式创建原始的 png,但更小,然后创建新的框架,在启动应用程序时询问系统哪个框架最适合屏幕并使用它(但我知道我不会很好,然后当然操作系统有时以不同的方式使用屏幕分辨率,使屏幕看起来更小或更大,如果你明白我的意思的话)。(我正在使用 Netbeans)。

非常感谢,我正在寻找序言来与您讨论这个问题,我相信这个问题也会引起许多其他人的关注。

最佳答案

Toolkit.getDefaultToolkit() 具有为您提供所需内容的方法,包括获取当前屏幕尺寸:

private void makeFrameFullSize(JFrame aFrame)
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
aFrame.setSize(screenSize.width, screenSize.height);
}

这篇文章讨论Resize image while keeping aspect ratio in Java .

现在您已经知道了屏幕尺寸,您可以计算图像高度/宽度与当前帧尺寸的比率,并根据当前帧尺寸与全屏尺寸的百分比差异进行缩放。

private Dimension get getFrameToScreenRatio(Frame aFrame){
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
return dimension.setSize(aFrame.getWidth()/dimension.getWidth(), aFrame.getHeight()/dimension.getHeight());
}

这是一个示例实用程序类,可以缩放图像以适合 Canvas (如背景图像)并缩放以适合 Canvas :

包net.codejava.graphics;

导入java.awt.Component;导入java.awt.Graphics;导入java.awt.Image;

/**
* This utility class draws and scales an image to fit canvas of a component.
* if the image is smaller than the canvas, it is kept as it is.
*
* @author www.codejava.net
*
*/
public class ImageDrawer {

public static void drawScaledImage(Image image, Component canvas, Graphics g) {
int imgWidth = image.getWidth(null);
int imgHeight = image.getHeight(null);

double imgAspect = (double) imgHeight / imgWidth;

int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();

double canvasAspect = (double) canvasHeight / canvasWidth;

int x1 = 0; // top left X position
int y1 = 0; // top left Y position
int x2 = 0; // bottom right X position
int y2 = 0; // bottom right Y position

if (imgWidth < canvasWidth && imgHeight < canvasHeight) {
// the image is smaller than the canvas
x1 = (canvasWidth - imgWidth) / 2;
y1 = (canvasHeight - imgHeight) / 2;
x2 = imgWidth + x1;
y2 = imgHeight + y1;

} else {
if (canvasAspect > imgAspect) {
y1 = canvasHeight;
// keep image aspect ratio
canvasHeight = (int) (canvasWidth * imgAspect);
y1 = (y1 - canvasHeight) / 2;
} else {
x1 = canvasWidth;
// keep image aspect ratio
canvasWidth = (int) (canvasHeight / imgAspect);
x1 = (x1 - canvasWidth) / 2;
}
x2 = canvasWidth + x1;
y2 = canvasHeight + y1;
}

g.drawImage(image, x1, y1, x2, y2, 0, 0, imgWidth, imgHeight, null);
}

关于java - 根据屏幕分辨率调整大小,Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com