擁有一張包含「0123456789:-」字符的位圖(每字符等寬),需在 MFC 中依目前時間動態繪製數字時鐘。核心思路:建立字符到位圖座標的映射,再用 BitBlt 或 StretchBlt 逐字複製像素區塊。
int GetCharIndex(TCHAR ch) {
static const TCHAR* map = _T("0123456789:-");
for (int i = 0; i < 12; ++i)
if (map[i] == ch) return i;
return -1; // 不支援字符
}
void CClockDlg::OnPaint() {
CPaintDC dc(this);
CTime now = CTime::GetCurrentTime();
CString str = now.Format(_T("%H:%M:%S")); // 格式如 14:05:09
CDC memDC;
memDC.CreateCompatibleDC(&dc);
CBitmap bmp;
bmp.LoadBitmap(IDB_DIGITS); // 包含 12 個字符的位圖資源
CBitmap* pOld = memDC.SelectObject(&bmp);
int charW = 20, charH = 30; // 單字符寬高
int x = 10, y = 10; // 起始座標
for (int i = 0; i < str.GetLength(); ++i) {
int idx = GetCharIndex(str[i]);
if (idx >= 0) {
dc.BitBlt(x, y, charW, charH, &memDC, idx * charW, 0, SRCCOPY);
x += charW;
}
}
memDC.SelectObject(pOld);
}
CBitmap::LoadBitmap 載入資源,避免重複載入。StretchBlt 並計算目標矩形。SetTimer(1, 1000, NULL) 每秒觸發 Invalidate() 更新顯示。擴充映射字串(如加入 APM、/ 等),並確保位圖按相同順序排列新字符即可。