這個函數已重復利用於多個手機利用軟件平台
用法:參數定義:str——要分割的字符串
font——字體
rowMaxW——分割後每行寬度
支撐標示符:
\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('哈');
int strID = 0;
int rowW = 0;
Vector strManager = new Vector();
char ch = ' ';
while(str.length() > strID){
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;
}
返回成果是一個已切割好的String數組,只要用一個循環打印出來就可以了
public static final void drawClipString(Graphics g,String[] clipStr,Font font,int color,int x,int y){
if(clipStr == null){
System.out.println("drawClipString");
return;
}
int FONTH = font.getHeight();
g.setFont(font);
g.setColor(color);
for(int i=0;i<clipStr.length;i++)
g.drawString(clipStr[ i ],x,y+i*FONTH,0);
}
參數定義:clipStr——先前分割好的字符串數組
font——字體
color——色彩
x,y——打印的屏幕地位
留心,切割和打印函數的字體參數必需保持一致!
半透明技巧(限MIDP2.0)
// 獲得半透明圖片,透明度從0到10共分為11個等級
public static final Image alfImage(Image img,int alf){
if(img == null){
System.out.println("alfImage");
return null;
}
if(alf < 0)
alf = 0;
else if(alf > 10)
alf = 10;
int imgW = img.getWidth();
int imgH = img.getHeight();
int[] RGBData = new int[imgW*imgH];
img.getRGB(RGBData,0,imgW,0,0,imgW,imgH);
int tmp = ((alf*255/10) << 24)|0x00ffffff;
for(int i=0;i<RGBData.length;i++)
RGBData &= tmp;
Image o_Img = Image.createRGBImage(RGBData,imgW,imgH,true);
return o_Img;
}
灰度圖轉化函數// 得到灰度圖
public static final Image grayImage(Image img){
if(img == null){
System.out.println("grayAlfImage");
return null;
}
int imgW = img.getWidth();
int imgH = img.getHeight();
int[] imgRGBData = new int[imgW*imgH];
img.getRGB(imgRGBData,0,imgW,0,0,imgW,imgH);
int ALF = 0;
int R = 0;
int G = 0;
int B = 0;
int GRAY = 0;
for(int i=0;i<imgRGBData.length;i++){
ALF = (imgRGBData >> 24) & 0xFF;
R = (imgRGBData >> 16) & 0xFF;
G = (imgRGBData >> 8) & 0xFF;
B = imgRGBData & 0xFF;
GRAY = (R*77+G*151+B*28 + 128)>>8;
imgRGBData = (ALF<<24)|(GRAY<<16)|(GRAY<<8)|GRAY;
}
return Image.createRGBImage(imgRGBData,imgW,imgH,true);
}