C 终端输出颜色

本文介绍了如何在C语言中使用ANSI转义码打印彩色文字,通过示例代码展示了如何输出绿色的"Hello,World!"。同时,详细解释了ANSI转义码的工作原理,包括CSI序列、SGR参数及其对应的效果,如颜色设置、样式调整等。这些知识对于理解和自定义终端输出的格式非常有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FROM:https://blog.youkuaiyun.com/aggresss/article/details/88116234?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase

从一个实例开始

在终端打印绿色的 “Hello, World!” 可以通过下面的C实现:

#include <stdio.h>

int main(int argc, const char * argv[])
{
    printf("\x1B[32mHello, World! \x1B[0m\n");
    printf("\033[32mHello, World! \033[0m\n");
    printf("\e[32mHello, World! \e[0m\n");
    return 0;
}

等同于用在 shell环境 用下面 echo 命令

echo -e "\033[32mHello, World! \033[0m"
echo -e "\x1B[32mHello, World! \x1B[0m"
echo -e "\e[32mHello, World! \e[0m"

hello_green
注释:

  • 在C中所有的ASCII码都可以用“\”加数字(一般是8进制或者16进制)来表示。而C中定义了一些字母前加"\"来表示常见的那些不能显示的ASCII字符,如\0,\t,\n等,就称为转义字符,因为后面的字符,都不是它本来的ASCII字符意思了。
  • \x1B 和 \033 分别是 27 的十六进制和八进制表示,也可以使用 \e 或者 \E 来表示。
  • ASCII 中的第27号字符 ESC(Escape)也就是转义字符。
  • “\033[32m” 中 “\033[” 表示一段 CSI 数据的开始,“m” 表示一段 CSI 数据的控制指令也是结束标志,“32” 是 CSI 的数据的内容,“m” 表示这段 CSI 数据是 SGR 格式,32则表示 SGR 的32号指令,也就是绿色。

CSI sequences

The ESC [ is followed by any number (including none) of “parameter bytes” in the range 0x30–0x3F (ASCII 0–9:;<=>?), then by any number of “intermediate bytes” in the range 0x20–0x2F (ASCII space and !"#$%&’()*+,-./), then finally by a single “final byte” in the range 0x40–0x7E (ASCII @A–Z[]^_`a–z{|}~).[18]:5.4
All common sequences just use the parameters as a series of semicolon-separated numbers such as 1;2;3. Missing numbers are treated as 0 (1;;3 acts like the middle number is 0, and no parameters at all in ESC[m acts like a 0 reset code). Some sequences (such as CUU) treat 0 as 1 in order to make missing parameters useful.[18]:F.4.2 Bytes other than digits and semicolon seem to not be used.[citation needed]
A subset of arrangements was declared “private” so that terminal manufacturers could insert their own sequences without conflicting with the standard. Sequences containing the parameter bytes <=>? or the final bytes 0x70–0x7E (p–z{|}~) are private.
The behavior of the terminal is undefined in the case where a CSI sequence contains any character outside of the range 0x20–0x7E. These illegal characters are either C0 control characters (the range 0–0x1F), DEL (0x7F), or bytes with the high bit set. Possible responses are to ignore the byte, to process it immediately, and furthermore whether to continue with the CSI sequence, to abort it immediately, or to ignore the rest of it.[citation needed]

SGR (Select Graphic Rendition) parameters

SGR sets display attributes. Several attributes can be set in the same sequence, separated by semicolons.[21] Each display attribute remains in effect until a following occurrence of SGR resets it.[1] If no codes are given, CSI m is treated as CSI 0 m (reset / normal).
In ECMA-48 SGR is called “Select Graphic Rendition”.[1] In Linux manual pages the term “Set Graphics Rendition” is used.

escape code

CodeEffectNote
0Reset / Normalall attributes off
1Bold or increased intensity 
2Faint (decreased intensity) 
3ItalicNot widely supported. Sometimes treated as inverse.
4Underline 
5Slow Blinkless than 150 per minute
6Rapid BlinkMS-DOS ANSI.SYS; 150+ per minute; not widely supported
7reverse videoswap foreground and background colors
8ConcealNot widely supported.
9Crossed-outCharacters legible, but marked for deletion.
10Primary(default) font 
11–19Alternative fontSelect alternative font {\displaystyle n-10} {\displaystyle n-10}
20FrakturRarely supported
21Doubly underline or Bold offDouble-underline per ECMA-48.[22] See discussion
22Normal color or intensityNeither bold nor faint
23Not italic, not Fraktur 
24Underline offNot singly or doubly underlined
25Blink off 
27Inverse off 
28Reveal conceal off 
29Not crossed out 
30–37Set foreground colorSee color table below
38Set foreground colorNext arguments are 5;n or 2;r;g;b, see below
39Default foreground colorimplementation defined (according to standard)
40–47Set background colorSee color table below
48Set background colorNext arguments are 5;n or 2;r;g;b, see below
49Default background colorimplementation defined (according to standard)
51Framed 
52Encircled 
53Overlined 
54Not framed or encircled 
55Not overlined 
60ideogram underline or right side lineRarely supported
61ideogram double underline or double line on the right side 
62ideogram overline or left side line 
63ideogram double overline or double line on the left side 
64ideogram stress marking 
65ideogram attributes offreset the effects of all of 60–64
90–97Set bright foreground coloraixterm (not in standard)
100–107Set bright background coloraixterm (not in standard)

参考文档

  1. ANSI
  2. ANSI escape code
  3. ASCII
<think>好的,我现在需要回答用户关于“终端输出RGB颜色”的问题。首先,我需要明确用户的具体需求是什么。终端输出通常指的是在命令行界面或终端窗口中显示文本,而RGB颜色则涉及如何用红、绿、蓝三个通道的组合来呈现颜色。用户可能想知道如何在终端输出带有特定RGB颜色的文本,或者了解终端支持RGB颜色的情况。 接下来,我需要回忆一下终端处理颜色的机制。传统的终端使用ANSI转义码来设置文本颜色,但这些颜色通常是预定义的,比如16色或256色模式,而不是直接的RGB值。不过,现在许多现代终端模拟器(如Windows Terminal、iTerm2、GNOME Terminal等)支持True Color(24位色),也就是直接使用RGB值来指定颜色。因此,用户的问题可能涉及到如何利用这些特性在终端中显示RGB颜色。 然后,我需要考虑用户可能的使用场景。例如,用户可能在编写脚本或程序时,希望输出带有特定颜色的文本,以增强可读性或视觉效果。因此,回答需要包括具体的实现方法,比如如何在不同的编程语言或shell脚本中使用ANSI转义码来设置RGB颜色。 同时,我需要验证不同终端对RGB颜色的支持情况。虽然很多现代终端支持,但仍有部分可能不支持,这时候可能需要回退到256色或16色模式。因此,在回答中应该提到兼容性问题,并建议用户检查他们使用的终端是否支持True Color。 此外,还需要提供具体的代码示例,例如在Bash、Python等语言中如何输出RGB颜色的文本。例如,使用ANSI转义码的格式,比如\033[38;2;R;G;Bm来设置前景色,其中R、G、B是0-255的数值。同时,需要提醒用户在输出后重置颜色,避免后续文本也带有颜色。 最后,可能需要补充一些测试方法,让用户确认他们的终端是否支持True Color。例如,运行一个脚本显示不同RGB颜色,或者参考在线资源进行测试。 总结下来,回答的结构应该包括:终端颜色支持的基本原理、现代终端的True Color支持、如何通过ANSI转义码使用RGB颜色、代码示例、兼容性注意事项以及测试方法。确保信息准确,步骤清晰,帮助用户逐步实现目标。</think>在终端输出RGB颜色需要依赖终端模拟器对**True Color(24位色)**的支持。以下是分步说明: --- ### 一、基本原理 1. **ANSI转义码**是终端控制颜色的基础语法 2. 传统模式仅支持**16色**或**256色** 3. 现代终端通过扩展支持直接使用RGB值: ```ansi \033[38;2;R;G;Bm # 设置前景色 \033[48;2;R;G;Bm # 设置背景色 ``` 其中`R,G,B`为0-255的整数值 --- ### 二、代码示例 #### Bash脚本示例 ```bash # 输出红色文字 echo -e "\033[38;2;255;0;0m这是红色文本\033[0m" # 绿色背景+白色文字 echo -e "\033[38;2;255;255;255;48;2;0;255;0m白字绿底\033[0m" ``` #### Python示例 ```python def rgb(r, g, b, text): return f"\033[38;2;{r};{g};{b}m{text}\033[0m" print(rgb(255, 128, 0, "这是橙色文字")) ``` --- ### 三、兼容性说明 1. **支持的终端**: - Windows Terminal(Win10+) - iTerm2(macOS) - GNOME Terminal(Linux) - 新版VS Code集成终端 2. **不支持的终端**: - 传统cmd/PowerShell - 部分SSH客户端 - 旧版Linux终端 --- ### 四、检测支持性 运行以下命令测试True Color支持: ```bash # 显示渐变颜色条 awk 'BEGIN{ for(r=0;r<256;r+=10) for(g=0;g<256;g+=10) printf "\033[48;2;%d;%d;0m " r,g printf "\033[0m\n" }' ``` --- ### 五、注意事项 1. 始终用`\033[0m`重置颜色 2. 避免滥用颜色影响可读性 3. 备选方案:使用256色模式(兼容性更好) 如需256色对照表,可告知我进一步说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值