4

Canvas含む がありLabelます。Canvasのサイズに合わせて、このラベルのフォントサイズを設定したいです。どうすればこれを行うことができますか?

編集:「含む」とは、キャンバスとラベルの境界が同じであることを意味します。

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();ます。.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 に答える