Graphics2D字符串根據文本框縮小字體自動換行


 

/**
*
*描述: 長字符串縮小字體自動換行
*@param g 
*@param text 字符串
*@param lineWidth 單元格寬度

*@param cellHeight 單元格高度
*@param x x坐標
*@param y y坐標
*@param cellFont 原字體

*/

public static void drawStringMultiLine(Graphics2D g, String text, int lineWidth, int cellHeight,int x, int y,Font cellFont) {
FontMetrics m = g.getFontMetrics();
if(m.stringWidth(text) < lineWidth) {
g.drawString(text, x, y);
} else {
/* 使用當前字體, 根據單元格寬度計算出應該打印行數 */
int strWidth = 0;
int widthLine = 1;
char[] chars = text.toCharArray();
for(int i = 0; i < chars.length; i++){
if(m.charWidth(chars[i]) > lineWidth){ //單個字比單元格寬,肯定縮小字體
widthLine = 10000;
break;
}

strWidth += m.charWidth(chars[i]);
if(strWidth > lineWidth){
widthLine++;
strWidth = 0;
i--;
}
}

String name = "Serif";
int style= Font.PLAIN;
int high = 16; //默認16號字
Font font = null;
if ( cellFont != null ){
name = cellFont.getName();
style= cellFont.getStyle();
high = cellFont.getSize();
}
int fontHeight = m.getAscent() + m.getDescent();

/* 計算能打出全部內容時的最大字體 */
int heightLine =2;//一個單元格只能寫2行
while ( widthLine > heightLine ){
/* 縮小字體,重復計算應該打印行數和允許打印行數 */
font = new Font( name, style, --high );

m = g.getFontMetrics( font );

/* 字體高度 */
fontHeight = m.getAscent() + m.getDescent();
if ( fontHeight <= 0 )
return;

strWidth = 0;
/* 使用當前字體, 根據單元格寬度計算出應該打印行數 */
widthLine = 1;
for(int i = 0; i < chars.length; i++){
if(m.charWidth(chars[i]) > lineWidth){ //單個字比單元格寬,肯定縮小字體
widthLine = 10000;
break;
}

strWidth += m.charWidth(chars[i]);
if(strWidth > lineWidth){
widthLine++;
strWidth = 0;
i--;
}
}

/* 使用當前字體時,根據單元格高度計算出允許打印行數 */
heightLine = 0;
while((fontHeight*heightLine) <= cellHeight)//最后一行沒有行間距
heightLine++;
heightLine--;

if(widthLine <= heightLine)
break;
}

Font oldFont = g.getFont();
Stroke oldStroke = g.getStroke();
g.setFont(font);
g.setStroke(new BasicStroke(1.0f));

/* 分行,計算各行文字內容 */
List<String> rows = new ArrayList<String>();
int fromIndex = 0;
strWidth = 0;
for ( int bgn=0; bgn<text.length(); ){//逐個字符累加計算長度,超過行寬,自動換行
strWidth += m.charWidth(chars[bgn]);

if(strWidth > lineWidth){
rows.add(text.substring(fromIndex, bgn));

strWidth = 0;
fromIndex = bgn;
}
else
bgn++;
}

if(fromIndex < text.length()) // 加上最后一行
rows.add(text.substring(fromIndex, text.length()));
String element;
for (Iterator iter = rows.iterator(); iter.hasNext();) {
element = (String) iter.next();
/* 繪制字符串 */
g.drawString(element, (float)x, (float)(y + m.getAscent()));
y += fontHeight;
}
g.setFont(oldFont);
g.setStroke(oldStroke);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM