由于SWT取用的是系统文字size,有个简单方式可以获取一整段包含中文\英文\数字\特殊字符的字符串宽度。

即是利用Label的computeSize方法,我们知道Label的大小可以随着内容文字伸缩,即可以推断,Label可以拿到准确的文字宽度。

代码如下:

 

package galaxy.ide.common.gef.util;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

/**
 * @author caiyu
 * @date 2016-5-16
 */
public class FontTool {

	private static FontTool instance;

	private FontTool() {
	};

	public static FontTool getInstance() {
		if (instance == null)
			synchronized (Object.class) {
				if (instance == null)
					instance = new FontTool();
			}
		return instance;
	}

	public int getWidth(String t, Font font) {
		Label text = new Label(Display.getCurrent().getActiveShell(), SWT.NONE);
		text.setText(t);
		int width = text.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
		text.dispose();
		return width;
	}

}

 

相关文章:

  • 2021-08-04
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2021-12-16
  • 2021-06-13
  • 2022-01-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
相关资源
相似解决方案