由于canvas中的drawstring 函數不能自動換行,是以在使用中必須考慮到換行問題
而換行很麻煩的是中英文混合,而且英文單詞不能拆開顯示。是以想了辦法,可能在英文單詞沒有空格的時候處理還有些小問題,以後繼續修改~~~~如有問題盡管提出
@string : 源字元串
@font: 顯示使用的字型
@FrameWidth : 螢幕寬度
public Vector dealstrings( String string ,Font font , int FrameWidth ){
int k = 0;
Vector tempvec = new Vector();
String tempstring = string;
int len = tempstring.length();
for( int j = 0 ,i = 0 ; i <= len ;i++ ){
//處理到字元串結束:
if(i >= tempstring.length())
{
tempvec.addElement(tempstring.substring(j,i));
break;
}
if (font.stringWidth(tempstring.substring(j,i)) <= FrameWidth && font.stringWidth(tempstring.substring(j,i+1)) > FrameWidth)
{
//當最後一個字元是中文,以及除空格以外的字元,符号時的處理
if( ((int)tempstring.charAt(i-1) >= 19968 && (int)tempstring.charAt(i-1) <= 171941) ||
( (int)tempstring.charAt(i-1) >= 0 && (int)tempstring.charAt(i-1) <= 64 && (int)tempstring.charAt(i-1) != 32 ) ||
( (int)tempstring.charAt(i-1) >= 91 && (int)tempstring.charAt(i-1) <= 96 ) ||
( (int)tempstring.charAt(i-1) >= 123 && (int)tempstring.charAt(i-1) <= 127 )
){
tempvec.addElement(tempstring.substring(j,i));
j=i;
continue;
}
//當最後一個字元或者下一個是空格
else { k = i;
while(tempstring.charAt(i) != ' ' && tempstring.charAt(i-1) != ' ')
{ i--;
if(i<=j){
i= k ;
break;
}
}
if(tempstring.charAt(i) == ' ' ){
tempvec.addElement(tempstring.substring(j,i));
i++;
j=i;
continue;
}
else {
tempvec.addElement(tempstring.substring(j,i));
j=i;
continue;
}
}
}
}
return tempvec;
}