Hexise's Blog

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

          日歷

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

          公告

          Free Domain Name Registration

          搜索

          •  

          最新評論

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

          Posted on 2006-12-29 11:21 Hexise 閱讀(2311) 評論(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;
          }
          主站蜘蛛池模板: 闽清县| 新密市| 凤庆县| 镇赉县| 呼玛县| 根河市| 富民县| 绥棱县| 玉环县| 崇州市| 张掖市| 博野县| 石狮市| 涿州市| 石泉县| 留坝县| 固原市| 石渠县| 平阴县| 凉城县| 千阳县| 威海市| 承德县| 湄潭县| 宁安市| 黎城县| 咸阳市| 明光市| 洮南市| 定结县| 淮北市| 筠连县| 图们市| 新乡县| 库车县| 嫩江县| 遂宁市| 乐都县| 石楼县| 兴城市| 古田县|