在J2ME中的Canvas上换行文本

时间:2010-08-06 04:50:51

标签: text java-me midp lcdui

我将开发j2me应用程序。我想知道,我如何根据J2ME中的屏幕宽度大小在画布上包装文本。

2 个答案:

答案 0 :(得分:5)

这是我在我的应用程序中使用的代码,它将包裹线条矢量,你可以在画布中的任何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;
   }

享受:)

答案 1 :(得分:1)

您需要自己计算要绘制的字符串的宽度并开始换行 (每次达到画布的最大宽度时,分割字符串。

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