Hexise's Blog

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

          日歷

          <2006年12月>
          262728293012
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          公告

          Free Domain Name Registration

          搜索

          •  

          最新評論

          SWT中獲取字符串占用像素數

          Posted on 2006-12-29 11:21 Hexise 閱讀(2315) 評論(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;
          }
          主站蜘蛛池模板: 永春县| 基隆市| 巩义市| 肃北| 遂川县| 昔阳县| 黔江区| 临沭县| 南华县| 霍林郭勒市| 承德市| 石河子市| 慈利县| 治多县| 子洲县| 乌苏市| 威宁| 中西区| 宁安市| 嵊州市| 沽源县| 宜兰县| 独山县| 沁阳市| 瓦房店市| 大名县| 保山市| 泰顺县| 商南县| 商河县| 元朗区| 分宜县| 民丰县| 建瓯市| 楚雄市| 文水县| 明溪县| 西华县| 白河县| 陵水| 鄂伦春自治旗|