以上是源碼及演示程序下載地址
(文章原地址 http://www.codeproject.com/Articles/24969/An-MFC-picture-control-to-dynamically-show-picture)
Introduction 介紹
這篇文章描述的是一個可以用於在對話框上顯示各種主流類型圖片 (如 BMP, GIF, JPEG...) 的MFC控件
Background 背景
我花了一些時間去搜索可以用於顯示圖片的MFC控件, 但卻沒有發現合適的。 所以我決定自己做一個輕量級,靈活度高的圖片控件(Picture control)去顯示各種類型的圖片。
Using the code 如何使用
這個控件內部使用的是GDI+庫,所以請在使用時把GdiPlus.lib加入到你的工程中(include libraries)。
使用這個控件時,先用VC++對話框設計器創建一個靜態文字控件(static text control) 。之後用MFC嚮導爲這個控件分配一個控件變量,類型定義爲CPictureCtrl。
現在你可以用你的控件裝載顯示圖片了,你只需要在這幾個CPictureCtrl::LoadFrom...
函數,
選擇合適你需要的的進行調用。裝載後控件會自動更新並顯示圖片。
要清除掉控件中顯示的圖片,調用CPictureCtrl::FreeImage
即可。
你的圖片會被自動調整到控件的大小,這可能會改變圖片原先的長寬比例。
class CPictureCtrl : public CStatic { public: //Constructor CPictureCtrl(void); //Destructor ~CPictureCtrl(void); public: //Loads an image from a file BOOL LoadFromFile(CString &szFilePath); //Loads an image from an IStream interface BOOL LoadFromStream(IStream* piStream); //Loads an image from a byte stream; BOOL LoadFromStream(BYTE* pData, size_t nSize); //Loads an image from a Resource // BOOL LoadFromResource(HMODULE hModule, LPCTSTR lpName, LPCTSTR lpType); //Overload - Single load function BOOL Load(CString &szFilePath); BOOL Load(IStream* piStream); BOOL Load(BYTE* pData, size_t nSize); // BOOL Load(HMODULE hModule, LPCTSTR lpName, LPCTSTR lpType); //Frees the image data void FreeData(); protected: virtual void PreSubclassWindow(); //Draws the Control virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual BOOL OnEraseBkgnd(CDC* pDC); private: //Internal image stream buffer IStream* m_pStream; //Control flag if a pic is loaded BOOL m_bIsPicLoaded; //GDI Plus Token ULONG_PTR m_gdiplusToken; };
Points of interest
這個控件是基於
CStatic
control
設計的(基類使用的是CStatic)。所以你可以使用CStatic
control的各種功能,但它並不會顯示任何文字。對GDI+庫的使用使其可以支持各種主流類型的圖片。
History 歷史
- 1.0 - Initial release.
- 1.1 - A bug when drawing the control without a loaded image was corrected.
- 1.2 - A bug when drawing the control was corrected.
Loading an image from a resource is disabled due to problems recognizing it correctly as an image.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
TEiseler Tester / Quality Assurance
Germany Member |