根据显示分辨率调整 SWT UI 个元素

Adapt SWT UI elements according to display resolution

我写了一个 GUI 应用程序,每个 shell 都在使用 GridLayout。在为 1280*1024 屏幕编写后,我意识到我应该让它在每个显示器上都可用,所以我添加了一个根据显示分辨率转换每个元素的高度和宽度的方法:

public static int widthconverter(double x){   
        int width = 0;
        width=(int) ((x/1280.0)*screenWidth);
        return width;
    }
public static int heightconverter(double x){
        int height = 0;
        height=(int) ((x/1024.0)*screenHeight);
        return height;
    }

这不符合我的要求。例如,使用 800*600 分辨率 shell 会调整大小,但宽度和高度有点太小而无法覆盖所有包含的元素。转到 4K 显示它也无法按需工作。

非常感谢任何解决此问题的想法。

您根本不应指定以像素为单位的绝对大小。

在许多情况下,控件的大小由其内容决定。通常要显示的字符的尺寸给出了一个很好的基本测量单位。下面的代码片段可以用作模板来确定字符串的大小(以像素为单位)。

Control control = ...
FontData[] fontData = control.getFont().getFontData();
GC gc = new GC( control );
Point size = gc.stringExtent( "Abc" );
// or
int height = gc.getFontMetrics().getHeight();
int avgWidth = gc.getFontMetrics().getAverageCharWidth();
gc.dispose();

要确定控件将占用多少像素来显示给定的文本,需要添加控件的 trim。例如

Rectangle trim = control.computeTrim( 0, 0, size.x, size.y );

如果使用 GridLayoutwidthHintheightHint 可以设置为 trim 的相应字段。

这是一种设计用户界面以适应多种屏幕分辨率的简单方法。

自从 Eclipse 4.6 发布后,SWT 还提供了 APIs 用于为高分辨率显示器加载图像。如果您为不同的屏幕分辨率提供图像,SWT 将选择一个合适的图像。 JFace 和 Eclipse 等上层 Platform/UI 也添加了对不同图像分辨率的支持。

另请参阅:

为遇到相同问题的任何人解决我的问题的代码:

static double screenWidth= screen.getWidth(); 
static double screenHeight=screen.getHeight(); 
int pixelPerInch=java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); 
static double scalingFactorheight=(screenWidth/screenHeight)/1.25;

public static int widthconverter(double x){
    int width = 0;
    width=(int) ((x/1280.0)*screenWidth);
    return width;
}

public static int heightconverter(double x){
    int height = 0;
    height=(int) ((x/1024.0)*screenHeight*scalingFactorheight);
    return height;
}