如何计算标签的最大适配字体大小?

我有一个包含LabelCanvas 。 我想根据canvas大小设置此标签的字体大小。 我们如何做到这一点?

编辑:“包含”意味着,canvas和标签边界是相同的。

编辑2:我有这个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); 

编辑3:这是我的字体大小计算器类的标签

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

我刚刚移植了上面的代码。

你可以通过GC.stringExtent();方法GC.stringExtent(); SWT中String的范围(长度GC.stringExtent(); 并且您需要Class FontData来获取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(); 

资料来源:

  • Stackoverflow:只改变SWT中的字体大小
  • Eclipse API:GC