首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java圖片上繪製文字自動換行實現方案

     編輯:程式設計綜合問答

需求分析

將字符串繪製到圖片上,要求:一行寫滿自動換行,類似文本編輯器的排版效果。

核心實現思路

  1. 創建BufferedImage作為畫布
  2. 獲取Graphics2D繪圖上下文
  3. 使用FontMetrics計算字符寬度
  4. 按寬度截斷字符串並逐行繪製

完整代碼示例

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()動態獲取

進階優化

  1. 支持中文按字符換行(非單詞)
  2. 添加文本對齊(左/中/右/兩端對齊)
  3. 處理超長不可分割字符串(強制截斷/縮放)
  4. 性能優化:複用Graphics2D、異步處理大圖

核心模式:測量→分行→逐行繪製,掌握此模式可應對各種文本排版需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved