【问题标题】:From hexadecimal string color to an RGB color从十六进制字符串颜色到 RGB 颜色
【发布时间】:2014-04-25 20:44:00
【问题描述】:

如何将hexadecimal 字符串颜色#FF0022 值转换为C++ 中的RGB 颜色?

来自:

#FF0022

r:255
g:0
b:34

我不知道该怎么做,我在谷歌上搜索过,但没有运气,请告诉我如何做,以便我了解更多信息。

【问题讨论】:

  • 我不相信您尝试使用 google,因为有大量结果(rgb 字符串到 c,rgb 字符串到值,...)
  • 如果你知道十六进制是什么,剩下的就很简单了:将它分成 3 个组成部分,FF、00 和 22。根据需要转换为小数。

标签: c++ colors hex rgb


【解决方案1】:

解析字符串,然后使用strtol() 将每组两个字符转换为十进制。

【讨论】:

  • @ooga 的回应与 SO q&a 社区的使命“为每个关于编程的问题建立详细答案库”的使命背道而驰。冒昧地传授纪律课程不是我们的工作
【解决方案2】:

这是一个代码示例:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

std::vector<std::string> SplitWithCharacters(const std::string& str, int splitLength) {
  int NumSubstrings = str.length() / splitLength;
  std::vector<std::string> ret;

  for (int i = 0; i < NumSubstrings; i++) {
     ret.push_back(str.substr(i * splitLength, splitLength));
  }

  // If there are leftover characters, create a shorter item at the end.
  if (str.length() % splitLength != 0) {
      ret.push_back(str.substr(splitLength * NumSubstrings));
  }


  return ret;
}

struct COLOR {
  short r;
  short g;
  short b;
};

COLOR hex2rgb(string hex) {
  COLOR color;

  if(hex.at(0) == '#') {
      hex.erase(0, 1);
  }

  while(hex.length() != 6) {
      hex += "0";
  }

  std::vector<string> colori=SplitWithCharacters(hex,2);

  color.r = stoi(colori[0],nullptr,16);
  color.g = stoi(colori[1],nullptr,16);
  color.b = stoi(colori[2],nullptr,16);

  return color;
}

int main() {
  string hexcolor;

  cout << "Insert hex color: ";
  cin >> hexcolor;

  COLOR color = hex2rgb(hexcolor);

  cout << "RGB:" << endl;
  cout << "R: " << color.r << endl;
  cout << "G: " << color.g << endl;
  cout << "B: " << color.b << endl;

  return 0;
}

【讨论】:

    猜你喜欢
    • 2012-11-01
    • 2019-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2017-04-11
    • 2018-10-22
    相关资源
    最近更新 更多