先根据宽度获取文本在这个宽度内显示多少字,并计算每个字的宽度
/*
* 获取文本一行的长度
*/
public static Object[] getNewString(Graphics2D g, String contentString, int WordMaxWidth) {
if (contentString == null) {
contentString = "";
}
Object[] results = new Object[3];
StringBuilder lineChars = new StringBuilder();//
List<Float> charsIndex = new ArrayList<>();//
StringBuilder sbTem = new StringBuilder();// 临时
int i = 0;
int size = 0;
Integer strWidth = 0;
for (; i < contentString.length(); i++) {
char c = contentString.charAt(i);
sbTem.append(c);
Integer strWidthTem = getStringWidth(g, sbTem.toString());
if (strWidthTem > WordMaxWidth) {
break;
}
lineChars.append(c);
Float b = Float.valueOf(strWidthTem - strWidth);
charsIndex.add(b);
size++;
strWidth = strWidthTem;
}
//英文保持单词完整
String regex = "^[a-zA-Z]+$";
if (size < contentString.length()) {
char c1 = contentString.charAt(size - 1);
String c2 = contentString.charAt(size) + "";
while (c1 != ' ' && c2.matches(regex)) {
lineChars.deleteCharAt(size - 1);
strWidth = getStringWidth(g, lineChars.toString());
size--;
c1 = contentString.charAt(size - 1);
c2 = contentString.charAt(size) + "";
}
}
// 如下个行字符的首字母,如果是特殊字符,则把本行的最后一个字符归入下一行开始
if (size < contentString.length()) {
char c = contentString.charAt(size);
if (c == ',' || c == '。' || c == ',') {
lineChars.deleteCharAt(size - 1);
charsIndex.remove(charsIndex.size() - 1);
strWidth = getStringWidth(g, lineChars.toString());
size--;
}
}
if (WordMaxWidth - strWidth > 2) {// 如果大于俩个像素,居中显示
BigDecimal blank = new BigDecimal(WordMaxWidth - strWidth);
BigDecimal chars = new BigDecimal(size);
BigDecimal d = blank.divide(chars, 2, BigDecimal.ROUND_DOWN);// 每两个字之间增加的空白数据
for (Integer j = 0; j < size; j++) {
charsIndex.set(j, charsIndex.get(j) + d.floatValue());
}
}
results[0] = lineChars.toString();
results[1] = charsIndex;
if (size < contentString.length()) {
results[2] = contentString.substring(size, contentString.length());
}
return results;
}
进行左右对齐操作
public static String drawStringLR(Graphics2D g, int WordMaxWidth, String contentString, float xAxis, float yAxis) {
// 先判断是否可以直接绘制,左对齐
int strLength = getStringWidth(g, contentString);
if (strLength <= WordMaxWidth) {
g.drawString(contentString, xAxis, yAxis);
return null;
}
// 左右对齐
Object[] results = getNewString(g, contentString, WordMaxWidth);
List<Float> indexList = (List<Float>) results[1];// 字符的宽度list,和字符一一对应
String lineString = results[0].toString();// 获取的字符
// 绘 制字符的时候添加间隔
for (int i = 0; i < lineString.length(); i++) {
g.drawString(String.valueOf(lineString.charAt(i)), xAxis, yAxis);
xAxis += indexList.get(i);
}
return (String) results[2];
}