效果:
代码:
java"> 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++;}}}
调用:
java"> // TODO 讲座名称String lectureName = "时空相分离调控的职务细胞信号转导";drawMyString(graphics, lectureName);