这个函数已反复应用于多个手机应用软件平台
用法:参数定义: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);
}