2010-08-06 67 views
0

我將開發j2me應用程序。我想知道,如何根據J2ME中的屏幕寬度大小將文本包裝到畫布上。在J2ME畫布上包裝文字

+1

接受一些答案! – Azlam 2010-08-19 18:21:42

回答

1

您需要計算要自己繪製的字符串的寬度,並在每次達到畫布的最大寬度時開始一個新行 (拆分字符串)。

void paint(Graphics _g) { 
    String t = "text to draw"; 
    int px_consumed = _g.getFont().substringWidth(t, 0, t.length())} 
}
5

這是我的代碼在我的應用程序中,它將換行向量和U可以在畫布上任意X點繪製。

public static Vector wrapToLines(String text, Font f, int maxWidth) { 
     Vector lines = new Vector(); 
     boolean paragraphFormat = false; 
     if (text == null) { 
      return lines; 
     } 
     if (f.stringWidth(text) < maxWidth) { 
      lines.add(text); 
      return lines; 
     } else { 

      char chars[] = text.toCharArray(); 
      int len = chars.length; 
      int count = 0; 
      int charWidth = 0; 
      int curLinePosStart = 0; 
      while (count < len) { 
       if ((charWidth += f.charWidth(chars[count])) > (maxWidth - 4) || count == len - 1) // wrap to next line 
       { 
        if (count == len - 1) { 
         count++; 
        } 
        String line = new String(chars, curLinePosStart, count - curLinePosStart); 
        if (paragraphFormat) { 
         int lastSpacePosition = line.lastIndexOf(" "); 
         String l = new String(chars, curLinePosStart, (lastSpacePosition != -1) ? lastSpacePosition + 1 : (count == len - 1) ? count - curLinePosStart + 1 : count - curLinePosStart); 
         lines.add(l); 
         curLinePosStart = (lastSpacePosition != -1) ? lastSpacePosition + 1 : count; 
        } else { 
         lines.add(line); 
         curLinePosStart = count; 
        } 
        charWidth = 0; 
       } 
       count++; 
      } 
      return lines; 

     } 
    } 

,雖然只運行在for循環

int y=0; 
int linespacing=4; 
    for(int i=0;i<lines.size();i++) 
    { 
    g.drawString((String)lines.get(i),10,y,0); 
    y+=(i!=lines.size()-1)?(font.getHeight()+linespacing):0; 
    } 

享受:)