今天使用GDI函数想往DC中画些字, 很奇怪的是无论使用CPen还是SetTextColor都无法改变文字的颜色。几经排查后终于发现问题所在:
源代码如下:
void CPrintPreviewDlg::Test()
{
int nWidth = 600;
int nHeight = 800;
CDC *pDC = GetDC();
CDC *pMemDC = new CDC;
pMemDC->CreateCompatibleDC(pDC);
// 创建Bitmap
CBitmap *pBitmap = new CBitmap;
// 注意下面这句, 创建兼容位图时必须使用pDC为参数
// 我本来是使用pMemDC作为参数,导致改变颜色不起作用
pBitmap->CreateCompatibleBitmap(pDC, nWidth, nHeight);
CBitmap *pOldBitmap = pMemDC->SelectObject(pBitmap);
// 画背景
CGdiObject *pOldObject = pMemDC->SelectStockObject(WHITE_BRUSH);
pMemDC->Rectangle(0, 0, nWidth, nHeight);
pMemDC->SelectObject(pOldObject);
// 输出文字
CFont font;
font.CreatePointFont(200, "宋体", pMemDC);
CFont *oldFont = pMemDC->SelectObject(&font);
CRect rect(1, 1, 100, 200);
pMemDC->SetTextColor(RGB(0, 0, 255));
pMemDC->DrawText("输出测试", rect, DT_LEFT|DT_SINGLELINE|DT_VCENTER);
pMemDC->SelectObject(oldFont);
pMemDC->SelectObject(pOldBitmap);
delete pBitmap;
delete pMemDC;
ReleaseDC(pDC);
}