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

Curses 庫顏色屬性完整指南

     編輯:關於C語言

顏色模型

Curses 採用 **RGB 三原色** 定義顏色,並透過 **顏色對** 將前景色與背景色綁定。終端機支援的顏色數由 COLORS、顏色對數由 COLOR_PAIRS 給出(通常 256 色、256 對)。

預設顏色常數 (索引 0-7)

常數索引RGB 近似值
COLOR_BLACK0(0, 0, 0)
COLOR_RED1(1000, 0, 0)
COLOR_GREEN2(0, 1000, 0)
COLOR_YELLOW3(1000, 1000, 0)
COLOR_BLUE4(0, 0, 1000)
COLOR_MAGENTA5(1000, 0, 1000)
COLOR_CYAN6(0, 1000, 1000)
COLOR_WHITE7(1000, 1000, 1000)

數值範圍 0-1000,對應 0%-100% 亮度。

核心 API

/* 全域變數:終端機能力 */
extern int COLORS;       // 最大顏色數
extern int COLOR_PAIRS;  // 最大顏色對數

/* 初始化顏色子系統,必須在 initscr() 後、任何顏色操作前呼叫 */
int start_color(void);

/* 定義顏色對:pair 索引(1..COLOR_PAIRS-1), f 前景, b 背景 */
int init_pair(short pair, short f, short b);

/* 重新定義基本顏色 RGB 分量 (color: 0..COLORS-1) */
int init_color(short color, short r, short g, short b);

/* 取得顏色對屬性值,用於 attron/attrset 等 */
chtype COLOR_PAIR(int n);

/* 範例:定義紅字藍底為 pair 1 */
start_color();
init_pair(1, COLOR_RED, COLOR_BLUE);
attron(COLOR_PAIR(1));
printw("紅字藍底");
attroff(COLOR_PAIR(1));

256 色 / 真彩色擴展

現代終端機(xterm-256color, vte, Windows Terminal)支援 256 色調色盤(0-15 系統色、16-231 6×6×6 立方體、232-255 灰階)與 24-bit 真彩色。ncurses 6.1+ 提供:

/* 設定顏色對使用 256 色索引 */
init_pair(10, 196, 21);  // 亮紅前景, 綠背景

/* 真彩色(需終端機支援,ncurses 透過 escape sequence 實現) */
#define TRUE_COLOR(r,g,b) ((r)<<16 | (g)<<8 | (b))
// 實際使用需檢查 terminfo 的 RGB 能力,或直接輸出 ESC[38;2;r;g;bm

實戰範例:彩色進度條

#include <curses.h>
#include <unistd.h>

int main() {
    initscr(); cbreak(); noecho(); curs_set(0);
    start_color();
    use_default_colors(); // 允許 -1 代表預設色

    // 定義漸變色對:綠→黃→紅
    for (int i = 0; i < 20; i++) {
        short r = (i * 1000) / 19;
        short g = 1000 - r;
        init_color(10 + i, r, g, 0);
        init_pair(1 + i, 10 + i, -1); // 前景漸變,背景預設
    }

    WINDOW *bar = newwin(3, 52, 5, 10);
    box(bar, 0, 0);
    wrefresh(bar);

    for (int p = 0; p <= 100; p += 5) {
        int seg = p / 5; // 0-20
        wattron(bar, COLOR_PAIR(1 + seg) | A_BOLD);
        mvwprintw(bar, 1, 1, "%3d%% [", p);
        int filled = p / 2;
        for (int i = 0; i < 50; i++) {
            waddch(bar, i < filled ? ACS_CKBOARD : ' ');
        }
        wprintw(bar, "]");
        wattroff(bar, COLOR_PAIR(1 + seg) | A_BOLD);
        wrefresh(bar);
        usleep(80000);
    }

    getch();
    endwin();
    return 0;
}

常見問題

  1. 未呼叫 start_color():所有 COLOR_PAIR 回傳 0,顏色無效。
  2. 顏色對索引從 1 開始:0 保留為預設(終端機預設前景/背景)。
  3. init_color 修改的是基本顏色定義:影響所有使用該索引的顏色對,慎用。
  4. 背景色透明問題:傳統 curses 不支援透明背景;use_default_colors() + init_pair(n, fg, -1) 可達到類似效果。
  5. 終端機類型不正確:確保 $TERM 為 xterm-256color 或同等支援 256 色的類型。

參考來源:「暗日」博客 原文連結

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