我們通常要對字符串進(jìn)行截取,以保證在畫(huà)面上顯示不全的地方Layout整齊劃一,Web畫(huà)面中尤其如此。但由于全角、半角、字符寬度不同而導致使用普通的substring()方法并不能滿(mǎn)足要求。所以,就google一下,參考了各種資料后,做了如下例子。
// 英文字體使用Arial,普通模式,大小12(單位是磅,中文中的“一號”,“二號”等這樣的分類(lèi)不支持。)
private static Font f = new Font("Arial", Font.PLAIN, 12);
// 我的例子中使用的是日文,字體MSGothic,普通模式,大小也是12.
private static Font jpf = new Font("MSGothic", Font.PLAIN, 12);
private static FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(f);
private static FontMetrics jpfm = Toolkit.getDefaultToolkit().getFontMetrics(jpf);
/* 上面的方法在java中不推薦使用,一般情況下可用new JComponent().getFontMetrics(font)替代之,但也不能保證總是正確的,
* 最好用實(shí)際繪制文字的JComponent對象來(lái)調用getFontMetrics(font)。
* private static JComponent t = new JLabel();
* private static FontMetrics fm = t.getFontMetrics(f);
*/
/*
*strValue: 需要截取的字符串
*MaxLenth:需要截取的最大長(cháng)度
* 需要注意的是:由于“W”所占的寬度最大,所以以其為基準,
* 最大長(cháng)度指的是MaxLenth個(gè)“W”所占的寬度,這樣就有了比較的基準。
*/
public static String trimDownText(String strValue, int MaxLenth) {
String strReturn = "";
String tmpChar = "";
int w_width = jpfm .stringWidth("W");
if (strValue != null) {
int chr_width = 0;
int totalWidth = 0;
for (int i = 0; i < strValue.length(); i++) {
// 取得某一個(gè)字符
tmpChar = strValue.substring(i, i + 1);
// 判斷是否是全角字符,半角使用英文字體,全角使用日文字體進(jìn)行計算寬度
if (tmpChar.getBytes().length == 1) {
chr_width = fm.stringWidth(tmpChar);
} else {
chr_width = jpfm.stringWidth(tmpChar);
}
// 總寬度大于指定的寬度后,截取終了。
if ((totalWidth + chr_width) > w_width * MaxLenth) {
break;
}
strReturn += tmpChar;
totalWidth += chr_width;
}
}
return strReturn;
}
.net下的解決方法改日再探討。
聯(lián)系客服