VC2008中使用GDI+(转)

转自http://blog.csdn.net/HeLiang7/archive/2008/05/18/2456453.aspx

研究了两天的GDI,发现太麻烦了。想到C#中的方便GDI+操作,于是查了一下,原来GDI+是COM的,新的SDK的一部分,VC也可以用。今天开始研究,把心得小结一下,所以这篇算是第一部分。

先把GDI+的资料说一下,既然是VS2008,当然MSDN里面是有的。地方是MSDN中的Platform SDK | Win32和COM开发 | Graphics and Multimedia | GDI+ 。然后是网上也比较多,google一下就行了。比较好的有http://www.codeproject.com/KB/GDI-plus/startinggdiplus.aspx,老外的这篇文章。
今天算是开了个头,说下怎么在VC中用GDI+,比C#当然是要麻烦一些,要多不少手脚。
以下只为VC2008为目标,VC6这个老古董就不研究它了。
1.         在“项目” | 属性 | 配置属性 | 链接器 | 输入 | 附加依赖项 | 中加上gdiplus.lib。或者在stdafx.h文件中加入编译宏
#pragma comment(lib, “gdiplus.lib”)
2.         在stdafx.h中加入一行
#include <gdiplus.h>
记得是最下面,但在#endif之前的地方。
3.         VC中使用GDI+必须要在使用之前和使用之后分别调用GdiplusStartup和GdiplusShutdown这两个函数,当然在MFC构架中在CWinApp子类中做这个比较好。MSDN中的例子是API方式的,下面给出的是MFC方式的。
在应用程序类中加入一个成员变量
ULONG_PTR m_gdiplusToken;
         这个玩意在GdiplusStartup初始化后,在要GdiplusShutdown引用到。
在InitInstance函数中加入
// Initialize GDI+
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);
当然,如果直接using namespace Gdiplus后,Gdiplus::就可以不要了。
最后在ExitInstance函数中加入
Gdiplus::GdiplusShutdown(m_gdiplusToken);
配置到此,就可以正常使用GDI+来进行工作了。当然一般的工作还是在CView的OnPaint里面来进行,使用Graphics来进行操作就行了。
4.     (新增)如果在成员变量中声明一个GDI+类的指针有问题,把所有CPP中的开头关于DEBUG的宏注释掉即可。此问题     在VS2008中出现过,但在VS2005中却没有,至少我用的版本是这样的。
复制一下引文中的一段代码为最后的说明,是OnPaint函数中的代码:

using namespace Gdiplus;
 
CPaintDC dc(this);
 
Graphics graphics(dc.m_hDC);
 
// Pen can also be constructed using a brush or another
//pen. There is a second parameter - a width which defaults to 1.0f
Pen blue (Color(255, 0, 0, 255));
 
Pen red (Color(255, 255, 0, 0));
int y = 256;
for (int x = 0; x < 256; x += 5)
...{
         graphics.DrawLine(&blue, 0, y, x, 0);
         graphics.DrawLine(&red, 256, x, y, 256); 
         y -= 5;
}                 
for (y = 0; y < 256; y++)
...{
         Pen pen(Color(y, 0, 255,0));
         // A green pen with shifting alpha 
         graphics.DrawLine(&pen, 0, y, 256, y); 
         // The sleep is to slow it down so you can watch the effect 
         Sleep(20);
}                 
for (x = 0; x < 256; x++)
...{
         Pen pen(Color(x, 255, 0, 255));
         // A green pen with shifting alpha 
         graphics.DrawLine(&pen, x, 100, x, 200);
         // The sleep is to slow it down so you can watch the effect
         Sleep(20); 
}

posted @ 2010-09-24 10:32  I'm 农民工  阅读(1435)  评论(1编辑  收藏  举报