效果:
代码:
public static void drawMyString(Graphics textGraphics, String text) {
// 每列显示的汉字数量
int columnSize = 7;
// 文字之间的垂直间距
int verticalSpacing = 75;
// 获取字体渲染上下文
FontMetrics fm = textGraphics.getFontMetrics();
// 获取字体的高度
int fontHeight = fm.getHeight();
System.out.println(fontHeight);
// 计算每列的宽度
int columnWidth = fontHeight + verticalSpacing;
// 设置初始位置
int x = 260;
int y = 450;
Font fontFour = new Font(" Source Han Sans CN", Font.BOLD, 100);
textGraphics.setFont(fontFour);
Color color = new Color(0, 88, 38);
textGraphics.setColor(color);
// // 绘制文字
int charCount = 0;
int totalColumns = (int)Math.ceil((double)text.length() / columnSize); // 总列数
int totalRows = Math.min(columnSize, text.length()); // 总行数
int remainingChars = text.length() % columnSize; // 最后一列剩余字符数
for (int columnIndex = 0; columnIndex < totalColumns; columnIndex++) {
for (int rowIndex = 0; rowIndex < totalRows; rowIndex++) {
if (charCount >= text.length()) break;
char ch = text.charAt(charCount);
// // 计算当前位置
int cx = x - columnIndex * columnWidth;
int cy = y + rowIndex * fontHeight + rowIndex * verticalSpacing; // 加入垂直偏移量
// 计算当前位置
// int cx = x - columnIndex * columnWidth;
// int cy = y + rowIndex * fontHeight + rowIndex * verticalSpacing + columnIndex ;
// 如果是最后一列并且不满 7 个字符,则需要将剩余字符居中
if (columnIndex == totalColumns - 1 && remainingChars > 0) {
int extraVerticalSpace = (columnSize - remainingChars) * (fontHeight + verticalSpacing) / 2;
cy += extraVerticalSpace;
}
// 绘制文字
textGraphics.drawString(String.valueOf(ch), cx, cy);
charCount++;
}
}
}
调用:
// TODO 讲座名称
String lectureName = "时空相分离调控的职务细胞信号转导";
drawMyString(graphics, lectureName);