C语言版GDI+应用例子 -- 画笔

GDI+ 提供了很多绘图方法,如直线、曲线、圆弧、矩形、椭圆、扇形、多边形以及路径线条等,这些图形都需要使用GDI+ 画笔对象。本文是个使用GDI+画笔画各种线段的例子:

#include "../../SampleCode/comcode/Application.h" #pragma hdrstop void DrawAlignmentRect(PGpGraphics g, PGpPen pen, PGpPen basePen, PenAlignment alignment) { PenSetAlignment(pen, alignment); GraphicsDrawRectangle(g, pen, 0, 0, 100, 100); GraphicsDrawRectangle(g, basePen, 0, 0, 100, 100); } void DrawDashStyleLine(PGpGraphics g, PGpPen pen) { // 自定义线条式样数组,数据含义为线段,空白,线段,空白..., // 实际线段长度为数据乘画笔宽度 REAL pat[4] = {5.0, 2.0, 1.0, 2.0}; DashStyle ds; for (ds = DashStyleSolid; ds <= DashStyleCustom; ds ++) { if (ds == DashStyleCustom) PenSetDashPattern(pen, pat, 4); PenSetDashStyle(pen, ds); GraphicsDrawLine(g, pen, 0, 0, 300, 0); GraphicsTranslate(g, 0, 20, MatrixOrderPrepend); } } void OnPaint(HDC DC) { // 定义复合线比例数组,2个数据为1组,组之间的大小为空白,共3条线 REAL cp[6] = {0.0f, 0.15f, 0.3f, 0.45f, 0.7f, 1.0f}; PGpGraphics g = GraphicsCreate(DC); // GDI+ 画布 PGpPen redPen = PenCreate(Red); // 红色笔 PGpPen greenPen = PenFromColor(Green, 20); // 绿色笔宽度20 // 设置消除锯齿作图方式(牺牲速度),可注释该句后比较作图效果 GraphicsSetSmoothingMode(g, SmoothingModeAntiAlias); // 画布平移,方便作图时使用相对坐标 GraphicsTranslate(g, 20, 20, MatrixOrderPrepend); // 按不同的对齐方式画同样的矩形,redPen为比较基准线 DrawAlignmentRect(g, greenPen, redPen, PenAlignmentCenter); // 居中(缺省) GraphicsTranslate(g, 0, 130, MatrixOrderPrepend); DrawAlignmentRect(g, greenPen, redPen, PenAlignmentInset); // 线内 // 复位图形变换 GraphicsResetTransform(g); GraphicsTranslate(g, 150, 20, MatrixOrderPrepend); // 用宽度6绿色笔画各种线条式样,线段两端为平头帽(缺省值) PenSetWidth(greenPen, 6); DrawDashStyleLine(g, greenPen); // 用宽度6绿色笔画各种线条式样,线段两端为圆头帽 PenSetDashCap(greenPen, DashCapRound); GraphicsTranslate(g, 0, 10, MatrixOrderPrepend); DrawDashStyleLine(g, greenPen); // 用宽度30红色笔画复合线条 GraphicsTranslate(g, -140, 20, MatrixOrderPrepend); PenSetWidth(redPen, 30); PenSetCompoundArray(redPen, cp, 6); // 设置复合线比例数组 GraphicsDrawLine(g, redPen, 0, 0, 440, 0); PenDelete(greenPen); PenDelete(redPen); GraphicsDelete(g); } //int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { InitApplication(hInstance, nCmdShow, FALSE); PaintProc = OnPaint; return RunApplication(TEXT("C语言Gdiplus演示例子 -- 线段"), 470, 350); } //---------------------------------------------------------------------------

例子代码使用的窗口框架代码和GDI+ C语言版本下载地址见《在C语言Windows应用程序中使用GDI+》。

下面是例子运行界面图:

C语言版GDI+应用例子 -- 画笔

关于GDI+画笔更多的内容可参见我的文章《GDI+ for VCL基础 -- 画笔》。

指导和建议请来信:[email protected][email protected]