Windows GDI 使用 COLORREF(RGB(r,g,b))表示顏色,Web 使用 #RRGGBB 十六進位字串。兩者互轉常見於網頁顏色套用至桌面應用。
CString szColor = "#0290D8";
szColor.Replace("#", "");
int rgb[6] = {0};
TCHAR hex[] = _T("0123456789ABCDEF");
for (int i = 0; i < 6; i++) {
TCHAR c = szColor.GetAt(i);
for (int j = 0; j < 16; j++) {
if (c == hex[j]) { rgb[i] = j; break; }
}
}
COLORREF color = RGB(rgb[0]*16 + rgb[1],
rgb[2]*16 + rgb[3],
rgb[4]*16 + rgb[5]);
缺點:程式碼冗長、效率低、大小寫需自行處理。
CString hexColor = "#0290D8";
DWORD r, g, b;
sscanf(hexColor, "#%2X%2X%2X", &r, &g, &b);
COLORREF color = RGB(r, g, b);
// 直接建立筆刷
CBrush brush;
brush.CreateSolidBrush(color);
優點:
%2X 自動處理大小寫十六進位。COLORREF c = RGB(2, 144, 216);
CString hex;
hex.Format("#%02X%02X%02X", GetRValue(c), GetGValue(c), GetBValue(c));
// hex = "#0290D8"