Curses 採用 **RGB 三原色** 定義顏色,並透過 **顏色對** 將前景色與背景色綁定。終端機支援的顏色數由 COLORS、顏色對數由 COLOR_PAIRS 給出(通常 256 色、256 對)。
| 常數 | 索引 | RGB 近似值 |
|---|---|---|
COLOR_BLACK | 0 | (0, 0, 0) |
COLOR_RED | 1 | (1000, 0, 0) |
COLOR_GREEN | 2 | (0, 1000, 0) |
COLOR_YELLOW | 3 | (1000, 1000, 0) |
COLOR_BLUE | 4 | (0, 0, 1000) |
COLOR_MAGENTA | 5 | (1000, 0, 1000) |
COLOR_CYAN | 6 | (0, 1000, 1000) |
COLOR_WHITE | 7 | (1000, 1000, 1000) |
數值範圍 0-1000,對應 0%-100% 亮度。
/* 全域變數:終端機能力 */
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));
現代終端機(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;
}
start_color():所有 COLOR_PAIR 回傳 0,顏色無效。init_color 修改的是基本顏色定義:影響所有使用該索引的顏色對,慎用。use_default_colors() + init_pair(n, fg, -1) 可達到類似效果。$TERM 為 xterm-256color 或同等支援 256 色的類型。參考來源:「暗日」博客 原文連結