核心 API
Graphics2D:2D 繪圖上下文
FontRenderContext:字體渲染上下文,包含抗鋸齒、分數度量等信息
Font.getStringBounds(String, FontRenderContext):返回字符串像素邊界矩形
完整代碼示例
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
public class StringPixelUtil {
public static Dimension getStringPixelSize(String text, Font font) {
// 創建一個虛擬圖像獲取 Graphics2D
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.setFont(font);
FontRenderContext frc = g.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(text, frc);
g.dispose();
return new Dimension((int)Math.ceil(bounds.getWidth()), (int)Math.ceil(bounds.getHeight()));
}
public static void main(String[] args) {
Font font = new Font("楷體", Font.ITALIC | Font.BOLD, 72);
Dimension size = getStringPixelSize("text", font);
System.out.println("寬: " + size.width + ", 高: " + size.height);
}
}
關鍵點解析
- 使用
BufferedImage 創建輕量級 Graphics2D,無需真實組件
FontRenderContext 影響度量精度,直接從 Graphics2D 獲取
Rectangle2D 提供浮點精度的寬高,建議向上取整
- 字體大小、樣式(粗體/斜體)直接影響像素尺寸
應用場景
- 自定義組件文字佈局計算
- 圖片上繪製文字前預測佔用區域
- 文本截斷省略號位置計算
- 打印預覽、報表生成