Hexise's Blog

          業(yè)精于勤荒于嬉 行成于思毀于隨
          posts - 13, comments - 12, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          SWT中獲取字符串占用像素數(shù)

          Posted on 2006-12-29 11:21 Hexise 閱讀(2309) 評論(0)  編輯  收藏 所屬分類: SWT/JFace
          可以使用GC類的getAdvanceWidth(char ch)獲取當(dāng)前字符所占的像素寬度.

          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

          可以如下面的程序使用該函數(shù):

          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是目標(biāo)字符串,font是你要設(shè)給字符串的字體對象:

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

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 额敏县| 青田县| 内黄县| 呼图壁县| 梓潼县| 天长市| 察隅县| 郧西县| 四子王旗| 理塘县| 漠河县| 临沧市| 家居| 新竹市| 锡林浩特市| 佛学| 安陆市| 山丹县| 安多县| 青阳县| 绥芬河市| 静安区| 裕民县| 淅川县| 公主岭市| 游戏| 江达县| 林州市| 玉屏| 萍乡市| 鹤岗市| 霍城县| 金华市| 大方县| 涿州市| 泰顺县| 辰溪县| 洛南县| 新竹市| 轮台县| 沧州市|