針對 MIDP 平台常見繪圖需求,提供三個可直接復用的工具方法:字串寬度限制自動斷行、圖片半透明混合、灰度轉換。代碼經多個手機應用驗證,相容性良好。
clipString()依指定字體與最大行寬,將長字串切割為字串陣列。支援 \n 強制換行、\t 插入兩全形空格。核心邏輯:逐字累加字符寬度,超寬則截斷當前行。
public static final String[] clipString(String str, Font font, int rowMaxW) {
if (str == null) return null;
if (rowMaxW < font.charWidth('哈')) rowMaxW = font.charWidth('哈');
Vector strManager = new Vector();
int strID = 0, rowW = 0;
while (str.length() > strID) {
char ch = str.charAt(strID);
switch (ch) {
case '\n':
strManager.addElement(str.substring(0, strID));
str = str.substring(strID + 1);
rowW = 0; strID = 0; break;
case '\t':
StringBuffer sb = new StringBuffer(str);
sb.deleteCharAt(strID); sb.insert(strID, " ");
str = sb.toString(); break;
default:
if (rowW + font.charWidth(ch) > rowMaxW) {
strManager.addElement(str.substring(0, strID));
str = str.substring(strID);
rowW = 0; strID = 0;
} else { rowW += font.charWidth(ch); strID++; }
}
}
strManager.addElement(str);
String[] o_Str = new String[strManager.size()];
strManager.copyInto(o_Str);
return o_Str;
}
配合 drawClipString(Graphics, String[], Font, int, int, int) 逐行繪製,注意字體參數必須一致。
alfImage()(需 MIDP 2.0)透過像素級 ARGB 操作實現 0~10 共 11 級透明度。取得像素陣列,構建遮罩 ((alpha*255/10) << 24) | 0x00ffffff,與每像素 AND 運算後重建 Image。
public static final Image alfImage(Image img, int alf) {
if (img == null) return null;
alf = Math.max(0, Math.min(10, alf));
int w = img.getWidth(), h = img.getHeight();
int[] rgb = new int[w * h];
img.getRGB(rgb, 0, w, 0, 0, w, h);
int mask = ((alf * 255 / 10) << 24) | 0x00ffffff;
for (int i = 0; i < rgb.length; i++) rgb[i] &= mask;
return Image.createRGBImage(rgb, w, h, true);
}
grayImage()依 ITU-R BT.601 加權公式 GRAY = (R*77 + G*151 + B*28 + 128) >> 8 計算亮度,保留 Alpha 通道,重建 RGB 圖片。
public static final Image grayImage(Image img) {
if (img == null) return null;
int w = img.getWidth(), h = img.getHeight();
int[] rgb = new int[w * h];
img.getRGB(rgb, 0, w, 0, 0, w, h);
for (int i = 0; i < rgb.length; i++) {
int ALF = (rgb[i] >> 24) & 0xFF;
int R = (rgb[i] >> 16) & 0xFF;
int G = (rgb[i] >> 8) & 0xFF;
int B = rgb[i] & 0xFF;
int GRAY = (R * 77 + G * 151 + B * 28 + 128) >> 8;
rgb[i] = (ALF << 24) | (GRAY << 16) | (GRAY << 8) | GRAY;
}
return Image.createRGBImage(rgb, w, h, true);
}
static final,適合放入工具類直接調用。Image 物件,頻繁調用請注意記憶體回收。