分类: LINUX
2008-12-15 10:31:58
Curses之前不支持彩色,后面支持了使用也很谨慎。
使用颜色之前要先检查终端支持的颜色类型,而后初始化颜色。初始化后,COLOR_PAIRS设置为最大值,64种颜色对很常见,一般为0-63。
#include
bool has_colors(void);
int start_color(void);
颜色对的初始化:
#include
int init_pair(short pair_number, short foreground, short
background);
int COLOR_PAIR(int pair_number);
int pair_content(short pair_number, short *foreground,
short *background);
curses.h中定义了一些基本颜色,COLOR_。pair_content可以更多的预定义的颜色对。
设置颜色对1为红字绿底。
init_pair(1,
COLOR_RED, COLOR_GREEN);
使用颜色对:
wattron(window_ptr,
COLOR_PAIR(1));
多种颜色对的混合使用:
wattron(window_ptr, COLOR_PAIR(1) | A_BOLD);
# cat color.c
/* First off, we check whether the program's
display terminal supports color.
If it does, we start the color
display. */
#include
#include
#include
#include
int main()
{
int i;
initscr();
if (!has_colors()) {
endwin();
fprintf(stderr, "Error - no color
support on this terminal\n");
exit(1);
}
if (start_color() != OK) {
endwin();
fprintf(stderr, "Error - could not
initialize colors\n");
exit(2);
}
/* We can now print out the allowed number of colors
and color pairs.
We create seven color pairs and display
them one at a time. */
clear();
mvprintw(5, 5, "There are %d COLORS,
and %d COLOR_PAIRS available",
COLORS, COLOR_PAIRS);
refresh();
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_GREEN);
init_pair(3, COLOR_GREEN, COLOR_RED);
init_pair(4, COLOR_YELLOW, COLOR_BLUE);
init_pair(5, COLOR_BLACK, COLOR_WHITE);
init_pair(6, COLOR_MAGENTA, COLOR_BLUE);
init_pair(7, COLOR_CYAN, COLOR_WHITE);
for (i = 1; i <= 7; i++) {
attroff(A_BOLD);
attrset(COLOR_PAIR(i));
mvprintw(5 + i, 5, "Color pair
%d", i);
attrset(COLOR_PAIR(i) | A_BOLD);
mvprintw(5 + i, 25, "Bold color
pair %d", i);
refresh();
sleep(1);
}
endwin();
exit(EXIT_SUCCESS);
}
为了兼容老的模式,还有颜色重定义功能:
#include
int
init_color(short color_number, short red, short green, short blue);