How to calculate the maximum font size for a shortcut?

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

EDIT: β€œcontains” means the borders of the canvas and the label are the same.

EDIT2: I have this for Swing, but I have not been able to 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 the font size calculator class for the 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 shortcut at the top of the window. I want its font size to match the size of the layer.

  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
source share
1 answer

I just ported the code above.

You can get the size (length) of a String in SWT using the GC.stringExtent(); method GC.stringExtent(); , and you'll need the FontData class to get the font height and Label font width.

  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:

+9
source

All Articles