首先應該計算需要換行的位置。這里我們以文字需要顯示的寬度linewd,和“/n”為換行的標志
        static public int ChangLine(String str, Font font, int linewd, boolean fullWord)
{ // 計算需要換行的位置  str:需要顯示的文字   font:文字的字體  linewd:需要顯示的寬度 
     int len = 0, wd = 0;
        for (int i = 0; i < str.length(); i++)  
             { 
                  if (str.charAt(i) == '/n')
                    {
                        if (i == 0)
                          return len + 1;
                        else
                          return len + 2;
                      }
                  wd += font.charWidth(str.charAt(i));
                   if (wd > linewd)
                    {
                        if (fullword)
                        {
                             for (int j = len; j >= 0; j--)
                                {
                                     if (str.charAt(j) < 0x30  str.charAt(j) >= 128)
                                      {
                                          len = j;
                                            break;
                                      }
                               }
                        }
                        return len + 1;
                   }
              len = i;
       }
           return 0;
}
計算好位置后,就開始為文字分行。
static public void DoLine(String infostr, int len)
    { // 為字符串分行,以便于顯示
     String tmpStr;
          Vector InfoLines = null;
          InfoLines = new Vector();
           int tmpint;  //需要換行的位置
     while (true)
          {
                tmpint = ChangLine(infostr, DefaultFont, len, false);
                if (tmpint == 0)
                {
                      InfoLines.addElement(infostr);
                      break;
                }
                else
               {
                    if (infostr.charAt(tmpint - 1) == '/n')
                         tmpStr = infostr.substring(0, tmpint - 1);
                    else
                         tmpStr = infostr.substring(0, tmpint);
                InfoLines.addElement(tmpStr);
                infostr = infostr.substring(tmpint, infostr.length());
            }
       }
}
以上就是處理文字分行的代碼。接下來我講介紹程序中制作文字的滾屏效果。請關注后續文章。
(出處:http://m.survivalescaperooms.com)
新聞熱點
疑難解答