如何在支持彩色字符的Linux终端上打印彩色字符?
如何判断终端是否支持色码?
发布于 2010-04-11 20:00:51
您需要输出ANSI colour codes。请注意,并非所有终端都支持此功能;如果不支持颜色序列,则会出现垃圾。
示例:
cout << "\033[1;31mbold red text\033[0m\n";这里,\033是ESC字符,ASCII27。后面跟着[,然后是用;分隔的零个或多个数字,最后是字母m。这些数字描述了从那时起要切换到的颜色和格式。
前景和背景颜色的代码为:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47此外,您还可以使用以下内容:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27有关其他不太受支持的代码,请参阅table on Wikipedia。
要确定您的终端是否支持颜色序列,请读取TERM环境变量的值。它应指定使用的特定终端类型(例如vt100、gnome-terminal、xterm、screen等)。然后在terminfo database中查找;检查colors功能。
发布于 2013-07-04 19:59:15
基础知识
我已经写了一个C++类,可以用来设置输出的前景和背景颜色。此示例程序用作打印This ->word<- is red.并将其格式化以使word的前景色为红色的示例。
#include "colormod.h" // namespace Color
#include <iostream>
using namespace std;
int main() {
Color::Modifier red(Color::FG_RED);
Color::Modifier def(Color::FG_DEFAULT);
cout << "This ->" << red << "word" << def << "<- is red." << endl;
}来源
#include <ostream>
namespace Color {
enum Code {
FG_RED = 31,
FG_GREEN = 32,
FG_BLUE = 34,
FG_DEFAULT = 39,
BG_RED = 41,
BG_GREEN = 42,
BG_BLUE = 44,
BG_DEFAULT = 49
};
class Modifier {
Code code;
public:
Modifier(Code pCode) : code(pCode) {}
friend std::ostream&
operator<<(std::ostream& os, const Modifier& mod) {
return os << "\033[" << mod.code << "m";
}
};
}高级
您可能想要向类中添加其他功能。例如,可以添加洋红色,甚至可以添加像粗体这样的样式。为此,只需向Code枚举添加另一个条目。This是一个很好的参考资料。
发布于 2012-10-06 22:16:58
在您准备输出任何需要的颜色之前,请确保您处于终端中:
[ -t 1 ] && echo 'Yes I am in a terminal' # isatty(3) call in C如果终端支持颜色,则需要检查终端功能
在使用terminfo (基于Linux)的系统上,您可以获得受支持的颜色数量,如下所示
Number_Of_colors_Supported=$(tput colors)在使用termcap (基于BSD)的系统上,您可以获得支持的颜色数量,如下所示
Number_Of_colors_Supported=$(tput Co)然后再做决定:
[ ${Number_Of_colors_Supported} -ge 8 ] && {
echo 'You are fine and can print colors'
} || {
echo 'Terminal does not support color'
}顺便说一句,不要像以前建议的那样对ESC字符使用着色。使用对终端功能的标准调用,该功能将为您分配特定终端支持的正确颜色。
基于BSD
fg_black="$(tput AF 0)"
fg_red="$(tput AF 1)"
fg_green="$(tput AF 2)"
fg_yellow="$(tput AF 3)"
fg_blue="$(tput AF 4)"
fg_magenta="$(tput AF 5)"
fg_cyan="$(tput AF 6)"
fg_white="$(tput AF 7)"
reset="$(tput me)"基于Linux
fg_black="$(tput setaf 0)"
fg_red="$(tput setaf 1)"
fg_green="$(tput setaf 2)"
fg_yellow="$(tput setaf 3)"
fg_blue="$(tput setaf 4)"
fg_magenta="$(tput setaf 5)"
fg_cyan="$(tput setaf 6)"
fg_white="$(tput setaf 7)"
reset="$(tput sgr0)"用作
echo -e "${fg_red} Red ${fg_green} Bull ${reset}"https://stackoverflow.com/questions/2616906
复制相似问题