`
withyou
  • 浏览: 439236 次
社区版块
存档分类
最新评论

SWT中获取字符串占用像素数

阅读更多
可以使用GC类的getAdvanceWidth(char ch)获取当前字符所占的像素宽度.

getAdvanceWidth

          public int getAdvanceWidth(char ch)

Returns the advance width of the specified character in the font which is currently selected into the receiver.

The advance width is defined as the horizontal distance the cursor should move after printing the character in the selected font.

Parameters:
ch - the character to measure
Returns:
the distance in the x direction to move past the character before painting the next
Throws:
SWTException -
  • ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed

可以如下面的程序使用该函数:

public static int getStringWidth(String string, Control control) {

   
int width = 0;
    GC gc 
= new GC(control);
    
for (int i = 0; i < string.length(); i++{
        
char c = string.charAt(i);
        width 
+= gc.getAdvanceWidth(c);
    }


    gc.dispose();
    
return width;
}

或者更通用的,其中string是目标字符串,font是你要设给字符串的字体对象:

public static int getStringWidth(String string, Font font){
    
int width = 0;
    Shell shell 
= new Shell();
    Label label 
= new Label(shell, SWT.NONE);
    label.setFont(font);
    GC gc 
= new GC(label);
    
for(int i=0;i<string.length();i++){
          
char c = string.charAt(i);
          width 
+= gc.getAdvanceWidth(c);
    }

    gc.dispose();
    shell.dispose();
    
return width;
}


Hexise 2006-12-29 11:21 发表评论
分享到:
评论
1 楼 javer 2010-10-22  
灰常感谢!

相关推荐

Global site tag (gtag.js) - Google Analytics