Graphics2D字符串根据文本框缩小字体自动换行

时间:2023-03-09 20:06:45
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);
}
}