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));
source share