將字符串繪製到圖片上,要求:一行寫滿自動換行,類似文本編輯器的排版效果。
BufferedImage作為畫布Graphics2D繪圖上下文FontMetrics計算字符寬度public static BufferedImage drawTextOnImage(BufferedImage src, String text,
Font font, Color color, int maxWidth, int lineHeight) {
// 創建副本避免修改原圖
BufferedImage result = new BufferedImage(
src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = result.createGraphics();
g2d.drawImage(src, 0, 0, null);
// 設置繪圖屬性
g2d.setFont(font);
g2d.setColor(color);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontMetrics fm = g2d.getFontMetrics();
int x = 50, y = 50; // 起始位置
// 自動換行邏輯
List lines = wrapText(text, font, maxWidth, fm);
for (String line : lines) {
g2d.drawString(line, x, y);
y += lineHeight;
}
g2d.dispose();
return result;
}
private static List wrapText(String text, Font font, int maxWidth, FontMetrics fm) {
List lines = new ArrayList<>();
String[] words = text.split(" ");
StringBuilder currentLine = new StringBuilder();
for (String word : words) {
String testLine = currentLine.length() == 0 ? word : currentLine + " " + word;
if (fm.stringWidth(testLine) <= maxWidth) {
currentLine.append(currentLine.length() == 0 ? "" : " ").append(word);
} else {
lines.add(currentLine.toString());
currentLine = new StringBuilder(word);
}
}
if (currentLine.length() > 0) lines.add(currentLine.toString());
return lines;
}
FontMetrics.stringWidth():精確測量文本像素寬度RenderingHints.KEY_TEXT_ANTIALIASING:開啟抗鋸齒BufferedImage.TYPE_INT_ARGB:支持透明通道fm.getHeight()動態獲取Graphics2D、異步處理大圖核心模式:測量→分行→逐行繪製,掌握此模式可應對各種文本排版需求。