Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate max fitting font size for Label?

I have a Canvas that contains a Label. I want to set font size of this label according to the Canvas size. How we can do this?

EDIT: "contains" means, Canvas and Label bounds are same.

EDIT2: I have this for Swing, but I couldn't convert it to 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: This is my font size calculator class for label

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);
    }
}

and this is my Label at the top of the window. I want its font size according the volume of Layer size.

    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));
like image 424
miqbal Avatar asked Dec 26 '22 14:12

miqbal


1 Answers

I have just ported the code above.

You can get the extent (length) of a String in SWT with the method GC.stringExtent(); and you need the Class FontData to get the font height and font width of the 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();

Sources:

  • Stackoverflow: Change just the font size in SWT
  • Eclipse API: GC
like image 141
jens-na Avatar answered Dec 31 '22 11:12

jens-na