SWT:获取字符串实际宽度

由于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;
	}

}

 

posted @ 2016-05-16 16:36  荒土  阅读(1226)  评论(0编辑  收藏  举报