经常听许多朋友说VC绘图总是出现各种各样的问题,比如说文字不显示啦,会闪烁之类的。
不说废话了,以下是本人总结的一段代码,有详细的注释,使用这段代码,可以解决这些麻烦。
void CDrawTestDlg::OnBnClickedButton1()
{
//窗体DC,作为物理屏
CDC* pDC = GetDC();
//内存DC,作为虚拟屏
CDC dcMem;
//准备关联位图与虚拟屏
dcMem.CreateCompatibleDC(NULL);
//定义一个位图对象
CBitmap bmp;
//获取窗体客户区尺寸
CRect rt;
GetClientRect(&rt);
int nWidth = rt.Width();
int nHeight = rt.Height();
//建立一个与窗体客户区显示兼容的位图
bmp.CreateCompatibleBitmap(pDC,nWidth,nHeight);
//关联位图与虚拟屏
CBitmap *pOldBit=dcMem.SelectObject(&bmp);
//------在虚拟屏上绘图------
//白色清屏
dcMem.FillSolidRect(0,0,nWidth,nHeight,RGB(255,255,255));
//画位图
CDC dcMemory;
dcMemory.CreateCompatibleDC(&dcMem);
CBitmap bmp1;
bmp1.LoadBitmapW(IDB_BITMAP1);
BITMAP bmpInfo;
bmp.GetBitmap(&bmpInfo);
CBitmap* pOldBitmap = dcMemory.SelectObject(&bmp1);
dcMem.StretchBlt(100,100,bmpInfo.bmWidth,bmpInfo.bmHeight,&dcMemory,0,0,bmpInfo.bmWidth,bmpInfo.bmHeight,SRCCOPY);
dcMemory.SelectObject(pOldBitmap);
//画文字
dcMem.TextOutW(200,100,_T("firefly"));
//将虚拟屏上的数据copy到物理屏上
pDC->BitBlt(0,0,nWidth,nHeight,&dcMem,0,0,SRCCOPY);
//释放资源
bmp.DeleteObject();
dcMem.DeleteDC();
ReleaseDC(pDC);
}