温馨提示×

C++ COLORREF与字符串互转怎么实现

c++
小亿
94
2023-10-24 13:18:13
栏目: 编程语言

要将COLORREF转换为字符串,您可以使用sprintf函数来实现。以下是一个示例代码:

COLORREF color = RGB(255, 0, 0); // 红色

char strColor[9];
sprintf(strColor, "#%02X%02X%02X", GetRValue(color), GetGValue(color), GetBValue(color));

std::string strColorString = strColor;

std::cout << strColorString << std::endl; // 输出字符串 "#FF0000"

要将字符串转换为COLORREF,您可以使用sscanf函数来实现。以下是一个示例代码:

std::string strColorString = "#FF0000";

int red, green, blue;
sscanf(strColorString.c_str(), "#%02X%02X%02X", &red, &green, &blue);

COLORREF color = RGB(red, green, blue);

std::cout << std::hex << color << std::endl; // 输出16进制表示的COLORREF值 0x000000FF

请注意,这些示例代码假设您正在使用Windows API的COLORREF类型,并且带有GetRValue、GetGValue和GetBValue等函数。如果您使用的是其他图形库或平台,请适当调整代码。

0