MIDP中處理文字的換行

來源:互聯網
上載者:User
在遊戲中,尤其是情景類的遊戲當中,往往需要大量情節介紹的文字。要在小小的手機螢幕上顯示這些文字,就必須對這些文字進行處理,使其能正確的換行,顯示在你想要顯示的寬度的範圍內。下面我就會詳細的介紹如何處理文字的換行。
          首先應該計算需要換行的位置。這裡我們以文字需要顯示的寬度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());

            }
       }
}

以上就是處理文字分行的代碼。接下來我講介紹程式中製作文字的滾屏效果。請關注後續文章。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.