MFC打开并显示位图

在OnDraw函数下添加如下内容:

    CDC memDC;//内存设备场景
    CBitmap cb;//位图类对象
    CRect rect;
    GetWindowRect(&rect);
    cb.LoadBitmap (IDB_BITMAP1);//载入资源
    memDC.CreateCompatibleDC (pDC);//创建内存设备上下文
    CBitmap *oldbitmap=NULL;
    oldbitmap=memDC.SelectObject (&cb);//将位图选入当前设备场景
    pDC->BitBlt (0,0,rect.Width (),rect.Height (),&memDC,0,0,SRCCOPY);//将内存场景的图象拷贝到屏幕上
    memDC.SelectObject (oldbitmap);

下面是MSDN中的例子:

Example

// This OnDraw() handler loads a bitmap from system resources,
//这个OnDraw()函数的句柄从系统资源中载入一个位图。 // centers it in the view, and uses BitBlt() to paint the bitmap bits.
//找到视图的中心点,使用BitBlt()函数绘制该文图。 void CBlat2View::OnDraw(CDC* pDC) { CBlat2Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // load IDB_BITMAP1 from our resources//从资源中载入IDB_BITMAP1 CBitmap bmp;//初始化一个CBitmap对象 if (bmp.LoadBitmap(IDB_BITMAP1))//如果载入成功,就进行以下操作 { // Get the size of the bitmap//得到该位图的大小 BITMAP bmpInfo; bmp.GetBitmap(&bmpInfo); // Create an in-memory DC compatible with the // display DC we're using to paint//创建一个与我们用来画图的显示DC兼容的内存DC CDC dcMemory; dcMemory.CreateCompatibleDC(pDC);//为什么要这么做?这是找到的网上比较贴切的回答:pDc是你当前窗口的设备上下文,一般的GDI操作,画线,输出文字,画图等都要通过它来完成,但画图的时候,需要用贴图函数BitBlt,这个函数需要通过另一个DC来传递位图数据。所以这里使用兼容DC就理所当然的了。//厄,今日又看了书,说是双缓存技术,是为了提高速度,糊涂了。。。 // Select the bitmap into the in-memory DC//把位图读入内存DC CBitmap* pOldBitmap = dcMemory.SelectObject(&bmp); // Find a centerpoint for the bitmap in the client area//在客户区找到一个适合位图的中心点 CRect rect; GetClientRect(&rect); int nX = rect.left + (rect.Width() - bmpInfo.bmWidth) / 2; int nY = rect.top + (rect.Height() - bmpInfo.bmHeight) / 2; // Copy the bits from the in-memory DC into the on- // screen DC to actually do the painting. Use the centerpoint // we computed for the target offset. pDC->BitBlt(nX, nY, bmpInfo.bmWidth, bmpInfo.bmHeight, &dcMemory, 0, 0, SRCCOPY);//什么是BitBlt呢?顾名思义BitBlt--Bit-Block transform也就是位块传输。就是从称为「来源」的设备内容中将一个矩形区的像素传输到称为「目的(destination)」的另一个设备内容中相同大小的矩形区 dcMemory.SelectObject(pOldBitmap); } else TRACE0("ERROR: Where's IDB_BITMAP1?/n"); }
 


 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值