Hexise's Blog

业精于勤荒于嬉 行成于思毁于随
posts - 13, comments - 12, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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

Posted on 2006-12-29 11:21 Hexise 阅读(2261) 评论(0)  编辑  收藏 所属分类: SWT/JFace
可以使用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;
}

只有注册用户登录后才能发表评论。


网站导航: