我有一个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));