天天看点

简单易用的CPicture 类

在VC编程中,常需要显示各种图片的功能,这个CPicture 类能满足其基本要求。以下是一个简单例子,能完成从资源或文件引入JPG、BMP等格式图片。

建立窗口工程MyImages,引入CPicture 类头文件

#include "Picture.h"

//声明成员变量

CPicture m_Picture;

一、 从资源中显示图片

1. 引入一JPG图片到资源中,名为“JPG”,ID:IDR_JPG1

2. 在OnInitDialog()中:

m_Picture.Load(IDR_JPG1,"JPG");//从资源中引入图片

3. 在OnPaint()中:

CPaintDC dc(this); // device context for painting

 m_Picture.UpdateSizeOnDC(&dc); // Get Picture Dimentions In Pixels

 CRect rect1;

 GetDlgItem(IDC_STATIC1) ->GetWindowRect(&rect1);//在固定的IDC_STATIC1中显示图片

 this ->ScreenToClient(rect1);

 m_Picture.Show(&dc,CPoint(rect1.left,rect1.top), CPoint(rect1.Width(),rect1.Height()), 0,0);//显示

OK!

二、打开文件选择显示图片

1. 打开文件对话框

CFileDialog dlg(TRUE);

 static char cFilter[] = "JPG文件 (*.jpg)\0*.jpg\0位图文件 (*.BMP)\0*.BMP\0\0";

 dlg.m_ofn.lpstrFilter = cFilter;

 int iResult;

 iResult = dlg.DoModal();

 CString strPictruemsg;

 if (iResult == IDOK)

 {

  strPictruemsg = dlg.GetFileName();//获得选择的文件路径

 }

 //载入图片

 if (strPictruemsg =="")

 {

  MessageBox("请选择要显示的图片。");

  return;

 }

 m_Picture.FreePictureData();//清除数据

 m_Picture.Load(strPictruemsg); // Load From a File

 //

//刷新窗口

 HWND hwnd = GetSafeHwnd(); //获取窗口的HWND

 ::InvalidateRect( hwnd, NULL, true ); //或者 ::InvalidateRect( hwnd, NULL, false );

 ::UpdateWindow(hwnd);

2. 在OnPaint()中使用同样代码

OK!

例子及CPicture 类源码下载:http://download.csdn.net/detail/dalongcoo/4486607