使用 3x8 位 RGB 代码(r、g、b)在终端中输出颜色,其中 r、g 和 b 分别从 0 到 255?

问题描述 投票:0回答:1

我知道我们可以按照此处所述在终端中打印颜色:C 中的 stdlib 和彩色输出以及此处:https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

是否可以使用 3x8 位 RGB 代码 (r、g、b) 输出更多自定义颜色,其中 r、g 和 b 从 0 到 255(理想的便携但至少对于 MacOS 11.6.1)?以下解决方案启用 255 种颜色,但仍不支持 rgb 编码。我想做的是调整 3 个参数(r、g 和 b)以获得所需的颜色

// inspired from http://jafrog.com/2013/11/23/colors-in-terminal.html
#include <stdio.h>

int main(void)
{
  int i;
  for (i = 0; i < 256; i++) 
  {
    printf("\e[38;5;%dm %3d\e[m", i, i);
  }
  return 0;
}


c terminal colors rgb
1个回答
0
投票

这是对我有用的代码:

#include <stdio.h>

#define ANSI_FONT_COL_RED       "\x1b[31m"
#define ANSI_FONT_COL_GREEN     "\x1b[32m"
#define ANSI_FONT_COL_YELLOW    "\x1b[33m"
#define ANSI_FONT_COL_BLUE      "\x1b[34m"
#define ANSI_FONT_COL_MAGENTA   "\x1b[35m"
#define ANSI_FONT_COL_CYAN      "\x1b[36m"
#define ANSI_FONT_COL_RESET     "\x1b[0m"
#define FONT_COL_CUSTOM         "\e[38;5;105m" // where 105 can go from 0 to 255
#define BCKGRD_COL_CUSTOM       "\e[48;5;30m" // where 30 can go from 0 to 255
#define FONT_COL_CUSTOM_RED     "\e[38;2;200;0;0m" 
#define FONT_COL_CUSTOM_GREEN   "\e[38;2;0;200;0m" 
#define FONT_COL_CUSTOM_BLUE    "\e[38;2;0;0;200m" 
#define BCKGRD_COL_CUSTOM_RED   "\e[48;2;200;0;0m" 
#define BCKGRD_COL_CUSTOM_GREEN "\e[48;2;0;200;0m" 
#define BCKGRD_COL_CUSTOM_BLUE  "\e[48;2;0;0;200m" 

int main (int argc, char const *argv[]) {

  printf(ANSI_FONT_COL_RED       "This font color is RED!"                  ANSI_FONT_COL_RESET "\n");
  printf(ANSI_FONT_COL_GREEN     "This font color is GREEN!"                ANSI_FONT_COL_RESET "\n");
  printf(ANSI_FONT_COL_YELLOW    "This font color is YELLOW!"               ANSI_FONT_COL_RESET "\n");
  printf(ANSI_FONT_COL_BLUE      "This font color is BLUE!"                 ANSI_FONT_COL_RESET "\n");
  printf(ANSI_FONT_COL_MAGENTA   "This font color is MAGENTA!"              ANSI_FONT_COL_RESET "\n");
  printf(ANSI_FONT_COL_CYAN      "This font color is CYAN!"                 ANSI_FONT_COL_RESET "\n");
  printf(FONT_COL_CUSTOM         "This font color is CUSTOM!"               ANSI_FONT_COL_RESET "\n");
  printf(FONT_COL_CUSTOM_RED     "This font color is CUSTOM_RED!"           ANSI_FONT_COL_RESET "\n");
  printf(FONT_COL_CUSTOM_GREEN   "This font color is CUSTOM_GREEN!"         ANSI_FONT_COL_RESET "\n");
  printf(FONT_COL_CUSTOM_BLUE    "This font color is CUSTOM_BLUE!"          ANSI_FONT_COL_RESET "\n");
  printf(BCKGRD_COL_CUSTOM_RED   "This background color is CUSTOM_RED!"     ANSI_FONT_COL_RESET "\n");
  printf(BCKGRD_COL_CUSTOM_GREEN "This background color is CUSTOM_GREEN!"   ANSI_FONT_COL_RESET "\n");
  printf(BCKGRD_COL_CUSTOM_BLUE  "This background color is CUSTOM_BLUE!"    ANSI_FONT_COL_RESET "\n");
  printf(BCKGRD_COL_CUSTOM       "This background color is CUSTOM!"         ANSI_FONT_COL_RESET "\n");
  printf(                        "This font color is NORMAL!\n");

  return 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.