Canvas 繪製文本時,drawString 不支持自動換行。需根據屏幕寬度、字體度量,將長字符串分割為多行再逐行繪製。
import java.util.Vector;
import javax.microedition.lcdui.Font;
/**
* 將字符串按像素寬度分割為多行,支持中英文混排、顯式換行符
* @param f 目標字體
* @param str 待分割字符串
* @param maxWidthPx 最大行寬(像素)
* @return Vector 每行文本
*/
public static Vector splitStringByWidth(Font f, String str, int maxWidthPx) {
if (str == null) return null;
Vector lines = new Vector();
char[] chars = str.toCharArray();
int lineWidth = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
int charWidth = f.charWidth(c);
// 遇到顯式換行符 或 加上當前字符超過最大寬度
if (c == '\n' || lineWidth + charWidth > maxWidthPx) {
lines.addElement(sb.toString());
sb = new StringBuffer();
lineWidth = 0;
if (c != '\n') { // 換行符不計入新行
sb.append(c);
lineWidth = charWidth;
}
} else {
sb.append(c);
lineWidth += charWidth;
}
}
if (sb.length() > 0) lines.addElement(sb.toString());
return lines;
}
// 在 Canvas.paint(Graphics g) 中
Vector lines = splitStringByWidth(font, longText, getWidth() - 4); // 留 2px 邊距
int y = startY;
int lineHeight = font.getHeight();
for (int i = 0; i < lines.size(); i++) {
String line = (String) lines.elementAt(i);
g.drawString(line, 2, y, Graphics.LEFT | Graphics.TOP);
y += lineHeight;
}
Font.charWidth(char) 而非字符數,完美支持中英文混排 (中文通常雙倍寬度)。\n 強制換行,不計入寬度。startIndex。通過 Font.charWidth 精確度量、Vector 動態存儲、逐行 drawString 繪製,即可在 Canvas 上實現高性能、支持中英文混排的自動換行文本顯示,是 J2ME 低級 UI 開發的基礎組件。