天天看點

簡單易用的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

繼續閱讀