温馨提示×

C++ COLORREF与字符串互转

c++
小亿
106
2023-12-19 11:40:06
栏目: 编程语言

在C++中,可以使用以下方法将COLORREF与字符串互相转换:

  1. 将COLORREF转换为字符串:
COLORREF color = RGB(255, 0, 0); // 示例红色
int r = GetRValue(color);
int g = GetGValue(color);
int b = GetBValue(color);
std::string colorStr = "#" + std::to_string(r) + std::to_string(g) + std::to_string(b);
  1. 将字符串转换为COLORREF:
std::string colorStr = "#FF0000"; // 示例红色
std::string rStr = colorStr.substr(1, 2); // 提取红色分量
std::string gStr = colorStr.substr(3, 2); // 提取绿色分量
std::string bStr = colorStr.substr(5, 2); // 提取蓝色分量
int r = std::stoi(rStr, nullptr, 16);
int g = std::stoi(gStr, nullptr, 16);
int b = std::stoi(bStr, nullptr, 16);
COLORREF color = RGB(r, g, b);

需要注意的是,以上方法仅适用于表示颜色的字符串格式为"#RRGGBB",其中RR表示红色分量的十六进制值,GG表示绿色分量的十六进制值,BB表示蓝色分量的十六进制值。其他格式的字符串需要相应的调整。

0