【问题标题】:How to make a color finding function with a hex color code in C++如何在 C++ 中使用十六进制颜色代码制作颜色查找功能
【发布时间】:2021-02-26 12:16:23
【问题描述】:

我正在尝试采用十六进制颜色代码并确定它是哪种颜色,我只使用五种基本颜色。这是我获取 rgb 并返回十六进制代码的代码。

string rgbtohex(int r, int g, int b, bool with_head)    //the following turns rgb values to hex values.
{
  stringstream ss;
  if (with_head)
  ss<< "#";
  ss<<hex<<(r << 16 | g << 8 | b );
  return ss.str();
}

我可以用这个输出十六进制代码

cout<<rgbtohex(r,b,g,true)<<endl;   //outputs hex color code

我想创建一个函数来获取 rgbtohex 输出并返回颜色。像这样的

string hextocolor()
{
 if(rgbtohex(r,g,b,true) = "#ff0000"){
 cout<<"Red"<<endl;
 }
}

【问题讨论】:

标签: c++ colors hex


【解决方案1】:

这适用于转为十六进制:

string rgbToHex(uint8_t r, uint8_t g, uint8_t b, bool withHead){
    stringstream ss;
    if (with_head)
        ss<< "#";
    
    ss << hex << r;
    ss << hex << g;
    ss << hex << b;

    return ss.str();
}

我认为您的原始解决方案也有效,问题是您在 hexToColor 的 if 语句中使用了 = 而不是 ==

【讨论】:

  • 你错过了std::setw(2) &lt;&lt; std::setfill('0'),因为黑色会显示为#000而不是#000000
【解决方案2】:

使用std::map,您可能会执行类似的操作

std::string toColorName(const std::string& hexColor)
{
    static const std::map<std::string, std::string> colors{
        {"#000000", "black"},
        {"#0000ff", "blue"},
        {"#00ff00", "green"},
        {"#ff0000", "red"},
        {"#ffffff", "white"}
    };
    return colors.at(hexColor);
}

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 2011-09-20
    • 2011-10-25
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多