来自于微软.net技术的c++托管扩展所包含的gdi+技术功能十分强大,本文将介绍如何使用gdi+的画刷来绘制文本。
一、使用画刷绘制文本的基本技术
本文所带的例子程序允许用户定义所要显示的文本、字体尺寸、显示文本所用的画刷(网格画刷或渐变画刷)以及绘制文本的颜色等。例子代码下载:gdiplustextwithbrushes.zip
下面是gdi+中使用渐变画刷或网格画刷绘制文本的基本步骤:
1、 在控件的绘制(paint)事件中添加一个事件处理函数。
在这个处理函数中进行绘制文本的相关处理,这样控件才能正确地进行重绘。
2、 获取一个图形(graphics)对象。
正如我们所熟悉的设备上下文一样,图形对象.net封装的一个绘制平面,例如,当在一个picturebox控件上进行绘制时,可以调用picturebox::creategraphics方法来获取一个graphics对象,并在控件上绘图时使用这个图形(graphics)对象。互联网上有很多例子都是这么做的,但是,有一个问题是,这样得到的graphics对象不是永久对象,如果用户从当前程序转到另一个应用程序并再次返回时,这个控件将无法正确地进行重绘。所以 ,要得当图形对象应当使用传递给控件paint方法的painteventargs对象中的graphics对象,代码如下所示:
| private: system::void pictext_paint(system::object * sender, system::windows::forms::painteventargs * e) { ... graphics* g = e->graphics; |
| using namespace system::drawing; ... font* font = new font(s"times new roman", 20, fontstyle::regular); |
| sizef textsize = g->measurestring(s"my sample text", font); |
| // hatchbrush example brush* brush = new hatchbrush(hatchstyle::cross, color::black, color::blue); // lineargradientbrush example rectanglef* rect = __nogc new rectanglef(pointf(0, 0), textsize); brush= new lineargradientbrush(*rect, color::black, color::blue, lineargradientmode::forwarddiagonal); |
| // use the windows-defined color for controls // and explicitly state the rectangle coordinates g->fillrectangle(systembrushes::control, pictext->left, pictext->top, pictext->right - pictext->left, pictext->bottom - pictext->top); // color the entire drawing surface using white g->clear(color::white); |
| // center the text on the drawing surface g->drawstring(txttodisplay->text, font, brush, (pictext->width - textsize.width) / 2, (pictext->height - textsize.height) / 2); |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器