4

我有一个Canvas包含一个Label. 我想根据画布大小设置这个标签的字体大小。我们怎么能做到这一点?

编辑:“包含”意味着,画布和标签边界是相同的。

EDIT2:我有这个用于 Swing,但我无法将它转换为 SWT;

Font labelFont = label.getFont();
String labelText = label.getText();
int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();
double widthRatio = (double)componentWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();
int fontSizeToUse = Math.min(newFontSize, componentHeight);

EDIT3:这是我的标签字体大小计算器类

public class FitFontSize {
    public static int Calculate(Label l) {
        Point size = l.getSize();
        FontData[] fontData = l.getFont().getFontData();
        GC gc = new GC(l);

        int stringWidth = gc.stringExtent(l.getText()).x;

        double widthRatio = (double) size.x / (double) stringWidth;
        int newFontSize = (int) (fontData[0].getHeight() * widthRatio);

        int componentHeight = size.y;
        System.out.println(newFontSize + " " + componentHeight);
        return Math.min(newFontSize, componentHeight);
    }
}

这是我在窗口顶部的标签。我希望它的字体大小根据图层大小的大小。

    Label l = new Label(shell, SWT.NONE);
    l.setText("TITLE HERE");
    l.setBounds(0,0,shell.getClientArea().width, (shell.getClientArea().height * 10 )/ 100);
    l.setFont(new Font(display, "Tahoma", 16,SWT.BOLD));
    l.setFont(new Font(display, "Tahoma", FitFontSize.Calculate(l),SWT.BOLD));
4

1 回答 1

10

我刚刚移植了上面的代码。

String您可以使用该方法在 SWT中获取 a 的范围(长度),GC.stringExtent();并且您需要 Class FontData来获取Label.

    Label label = new Label(parent, SWT.BORDER);
    label.setSize(50, 30);
    label.setText("String");

    // Get the label size and the font data
    Point size = label.getSize();
    FontData[] fontData = label.getFont().getFontData();
    GC gc = new GC(label);

    int stringWidth = gc.stringExtent(label.getText()).x;

    // Note: In original answer was ...size.x + (double)..., must be / not +
    double widthRatio = (double) size.x / (double) stringWidth;
    int newFontSize = (int) (fontData[0].getHeight() * widthRatio);

    int componentHeight = size.y;
    int fontsizeToUse = Math.min(newFontSize, componentHeight);

    // set the font
    fontData[0].setHeight(fontsizeToUse);
    label.setFont(new Font(Display.getCurrent(), fontData[0]));

    gc.dispose();

资料来源:

于 2012-11-27T08:40:50.153 回答