首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 圖形繪製:字體、顏色與文本繪製完整指南

     編輯:Java 相關知識

在 Java AWT/Swing 繪圖中,文本繪製與顏色管理是基礎也是高頻操作。本文系統整理 Graphics 文本繪製方法、Font 字體構建、Color 顏色創建與漸變,附帶完整可運行示例。

一、文本繪製三大核心方法

方法參數說明
drawString(String str, int x, int y)字符串、基線起點座標最常用,(x,y) 為基線左端點,非矩形左上角
drawChars(char[] data, int offset, int len, int x, int y)字符數組、偏移、長度、座標繪製字符數組片段
drawBytes(byte[] data, int offset, int len, int x, int y)字節數組、偏移、長度、座標繪製字節數組片段(少用)

座標陷阱:y 是基線位置。欲獲取文本邊界矩形,請用 FontMetrics:

FontMetrics fm = g.getFontMetrics();
int ascent = fm.getAscent();    // 基線以上高度
int descent = fm.getDescent();  // 基線以下深度
int height = fm.getHeight();    // 行高 = ascent + descent + leading
int width = fm.stringWidth(str); // 字符串寬度

二、Font 字體構建與屬性

// 構造:字體名、風格、字號(pt)
Font f1 = new Font("微軟雅黑", Font.PLAIN, 16);
Font f2 = new Font("Consolas", Font.BOLD | Font.ITALIC, 14); // 風格可組合

// 常用屬性獲取
String name = font.getName();   // 字體名
int style = font.getStyle();    // 風格掩碼
int size = font.getSize();      // 字號
boolean plain = font.isPlain();
boolean bold = font.isBold();
boolean italic = font.isItalic();

常見字體名(跨平台建議用邏輯名)

  • 邏輯名:Serif(襯線)、SansSerif(無襯線)、Monospaced(等寬)、Dialog、DialogInput — JDK 保證映射到平台合適字體。
  • 物理名:微軟雅黑、宋體、Arial、Times New Roman — 僅在安裝該字體的系統可用。

三、Color 顏色創建與使用

1. 預定義常量

Color.RED, BLUE, GREEN, BLACK, WHITE, YELLOW, CYAN, MAGENTA, GRAY, LIGHT_GRAY, DARK_GRAY,
ORANGE, PINK, TRANSPARENT (JDK 1.7+)

2. RGB 構建

Color c1 = new Color(255, 128, 0);           // RGB 0-255
Color c2 = new Color(0xFF8000);              // 十六進制整數
Color c3 = new Color(1.0f, 0.5f, 0.0f);      // RGB 0.0-1.0 float
Color c4 = new Color(255, 128, 0, 128);      // RGBA 帶透明度 (0-255)
Color c5 = new Color(0.0f, 0.5f, 1.0f, 0.5f); // RGBA float

3. HSB 色彩空間

Color c = Color.getHSBColor(0.5f, 1.0f, 1.0f); // 色相、飽和度、亮度 0.0-1.0

4. 顏色應用

g.setColor(Color.RED);        // 設置前景色(繪圖/文本色)
g.setBackground(Color.WHITE); // 設置組件背景色(需組件 opaque=true)
Component comp = ...;
comp.setBackground(Color.YELLOW);

四、綜合示例:彩虹字體展示

public class FontColorDemo extends JPanel {
    private final Font[] fonts = {
        new Font("Serif", Font.PLAIN, 18),
        new Font("SansSerif", Font.BOLD, 16),
        new Font("Monospaced", Font.ITALIC, 14),
        new Font("Dialog", Font.BOLD | Font.ITALIC, 16)
    };
    private final String[] texts = {
        "18pt Plain Serif",
        "16pt Bold SansSerif",
        "14pt Italic Monospaced",
        "16pt Bold+Italic Dialog"
    };

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // 開啟抗鋸齒

        for (int i = 0; i < fonts.length; i++) {
            // 漸變顏色:HSB 色相輪換
            Color c = Color.getHSBColor(i * 0.25f, 0.8f, 0.9f);
            g2.setFont(fonts[i]);
            g2.setColor(c);
            g2.drawString(texts[i], 20, 40 + i * 35);
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Font & Color Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new FontColorDemo());
        f.setSize(400, 300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

五、進階技巧

  1. 抗鋸齒:g2.setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON) — 文本邊緣平滑。
  2. 文本佈局:TextLayout 支持雙向文本、連字、複雜腳本(阿拉伯文、印地文等)。
  3. 字體回退:邏輯字體名會自動回退;物理字體可用 Font.createFont() 載入 TTF 文件嵌入應用。
  4. 性能提示:Font、Color 為不可變對象,重用實例,避免在 paintComponent 中重複 new。

掌握字體構建、顏色空間、基線座標系與 FontMetrics,是實現精美 UI、報表導出、圖表繪製、遊戲 HUD 的核心基本功。

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