一行代碼搞定
int iRed = GetRValue(m_cColor);
int iGreen = GetGValue(m_cColor);
int iBlue = GetBValue(m_cColor);
CString szColor;
szColor.Format(_T("#%02X%02X%02X"), iRed, iGreen, iBlue);
關鍵點解析
GetRValue/GetGValue/GetBValue:從 COLORREF (0x00BBGGRR) 提取 R/G/B 分量(各 0-255)
%02X:大寫十六進制,不足兩位左補 0
_T():確保 Unicode/ANSI 構建下均正常工作
- 結果示例:
#FF8000(橙色)
反向操作:字符串轉 COLORREF
COLORREF StringToColorRef(const CString& str)
{
// 假設格式 "#RRGGBB" 或 "RRGGBB"
CString s = str;
if (s[0] == _T('#')) s = s.Mid(1);
if (s.GetLength() != 6) return RGB(0,0,0);
int r = _tcstol(s.Mid(0,2), NULL, 16);
int g = _tcstol(s.Mid(2,2), NULL, 16);
int b = _tcstol(s.Mid(4,2), NULL, 16);
return RGB(r, g, b);
}
擴展:帶 Alpha 通道的 #AARRGGBB
// 若使用 32 位色值 (ARGB)
COLORREF argb = 0x80FF8000; // 半透明橙色
CString szARGB;
szARGB.Format(_T("#%02X%02X%02X%02X"),
(argb >> 24) & 0xFF, // Alpha
(argb >> 16) & 0xFF, // Red
(argb >> 8) & 0xFF, // Green
argb & 0xFF); // Blue
// 結果:#80FF8000