这里讲的是如何将一副位图(.bmp文件)作为窗口显示的背景。
1. 创建MFC AppWizard[exe]单文档工程
2. 插入位图资源
插入资源—选Bitmap---选择所需要的图片
3. 创建一个兼容设备表DC
CDC dcCompatible;
dcCompatible.CreateCompatibleDC(pDC);
4. 装入位图资源
CBitmap bmp;
bmp.LoadBitmap(IDB_BACKGROUND);
5. 将位图选入兼容设备表DC
dcCompatible.SelectObject(&bmp);
6. 将兼容设备描述表上的内容复制到当前设备描述表上
CRect rect;
GetClientRect(&rect);//获取客户区矩形大小pDC->BitBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,SRCCOPY);
函数BitBlt用于将源DC上的位图复制到目的DC。原形如下
BOOL BitBlt(
HDC hdcDest,//指向包含位图的目的DC
int nXDest,
int nYDest, //目的DC的左上角的x和y坐标
int nWidth,
int nHeight,//表示目的DC或源位图的宽度和高度
HDC hdcSrc, // 指向包含位图的源DC
int nXSrc,
int nYSrc, // 源位图左上角的x和y坐标
DWORD dwRop //表示贴图的模式
);
SRCCOPY表示直接将源位图复制到目的DC中。
代码如下:
void CMyView::OnDraw(CDC* pDC)
{
CMyDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
CDC dcCompatible; //创建一个兼容DC
dcCompatible.CreateCompatibleDC(pDC); //创建及装入位图资源
CBitmap bmp;
bmp.LoadBitmap(IDB_BACKGROUND); //载入位图
dcCompatible.SelectObject(&bmp); //将位图选入兼容设备表对象DC
CRect rect; //定义对象
GetClientRect(&rect); //获取当前客户区的大小//将兼容DC上的内容复制到当前DC上
pDC->BitBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,SRCCOPY);
// TODO: 在此处为本机数据添加绘制代码
}
上面的代码例子是按原图大小作为背景。
7. 修改位图背景
void CMyView::OnDraw(CDC*pDC)
{
CMyDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
CDC dcCompatible; //创建一个兼容DC
dcCompatible.CreateCompatibleDC(pDC); //创建及装入位图资源
CBitmapbmp;
bmp.LoadBitmap(IDB_BACKGROUND); //载入位图
dcCompatible.SelectObject(&bmp); //将位图选入兼容设备表对象DC
CRectrect; //定义对象
GetClientRect(&rect); //获取当前客户区的大小//将兼容DC上的内容复制到当前DC上
//pDC->BitBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,SRCCOPY);
BITMAPbitmap;
bmp.GetBitmap(&bitmap);//将位图的信息及属性取出放到先前定义好的bitmap变量中
//pDC->StretchBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);
pDC->StretchBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);
// TODO: 在此处为本机数据添加绘制代码
}
按窗口调整图片,显示完整图片,
BOOL StretchBlt(
HDC hdcDest, // handle to destination DC
int nXOriginDest, // x-coord of destination upper-left corner
int nYOriginDest, // y-coord of destination upper-left corner
int nWidthDest, // width of destination rectangle
int nHeightDest, // height of destination rectangle
HDC hdcSrc, // handle to source DC
int nXOriginSrc, // x-coord of source upper-left corner
int nYOriginSrc, // y-coord of source upper-left corner
int nWidthSrc, // width of source rectangle
int nHeightSrc, // height of source rectangle
DWORD dwRop // raster operation code
);