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

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

ExpandedBlockStart.gif ContractedBlock.gif public   static   int  getStringWidth(String string, Control control)  dot.gif {
InBlock.gif
InBlock.gif   
int width = 0;
InBlock.gif    GC gc 
= new GC(control);
ExpandedSubBlockStart.gifContractedSubBlock.gif    
for (int i = 0; i < string.length(); i++dot.gif{
InBlock.gif        
char c = string.charAt(i);
InBlock.gif        width 
+= gc.getAdvanceWidth(c);InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    gc.dispose();InBlock.gif
InBlock.gif    
return width;
ExpandedBlockEnd.gif}

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

ExpandedBlockStart.gif ContractedBlock.gif public   static   int  getStringWidth(String string, Font font) dot.gif {InBlock.gif
InBlock.gif    
int width = 0;
InBlock.gif    Shell shell 
= new Shell();
InBlock.gif    Label label 
= new Label(shell, SWT.NONE);
InBlock.gif    label.setFont(font);
InBlock.gif    GC gc 
= new GC(label);
ExpandedSubBlockStart.gifContractedSubBlock.gif    
for(int i=0;i<string.length();i++)dot.gif{
InBlock.gif          
char c = string.charAt(i);
InBlock.gif          width 
+= gc.getAdvanceWidth(c);InBlock.gif
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    gc.dispose();
InBlock.gif    shell.dispose();InBlock.gif
InBlock.gif    
return width;
ExpandedBlockEnd.gif}
90683.html

Hexise 2006-12-29 11:21 发表评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值