GDI+画刷(Brush)

发布时间 2023-07-18 10:25:27作者: 左边的翼

一、画刷简介

  在官方文档中对Brush类的描述为"The Brush class is an abstract base class that defines a Brush object...",通过描述可看出,Brush类为一个抽象基类,在应用Brush对象时只能通过其实现子类实例化应用;官方文档中可实例化的Brush类有四种,分别为HatchBrush、LinearGradientBrush、SolidBrush、TextureBrush。

二、SolidBrush

  该方法用某种指定的颜色创建画刷并使用,代码效果如下图所示:

1 Graphics graphics(dc);
2 SolidBrush br(Color(0,0,255));
3 graphics.FillRectangle(&br, 50, 50, 200, 100);

三、HatchBrush

  该画笔在应用过程中需要指定其前景色、后景色及样式,在其构造函数HatchBrush(HatchStyle h, const Color fColor, const Color bColor)中可看出来。针对该画笔样式进行如下代码效果展示:

 1 Graphics graphics(dc);
 2 Gdiplus::HatchBrush hra(Gdiplus::HatchStyle::HatchStyleDiagonalBrick, Color(255, 0, 0), Color(0, 255, 0));
 3 graphics.FillRectangle(&hra, 10, 20, 200, 20);
 4 
 5 Gdiplus::HatchBrush hrb(Gdiplus::HatchStyle::HatchStyleCross, Color(0, 255, 0), Color(255, 0, 0));
 6 graphics.FillRectangle(&hrb, 10, 50, 200, 20);
 7 
 8 Gdiplus::HatchBrush hrc(Gdiplus::HatchStyle::HatchStyleDiagonalCross, Color(255, 0, 0), Color(0, 255, 0));
 9 graphics.FillRectangle(&hrc, 10, 80, 200, 20);
10 
11 Gdiplus::HatchBrush hrd(Gdiplus::HatchStyle::HatchStyleDivot, Color(0, 255, 0), Color(255, 0, 0));
12 graphics.FillRectangle(&hrd, 10, 110, 200, 20);
13 
14 Gdiplus::HatchBrush hre(Gdiplus::HatchStyle::HatchStyleDottedDiamond, Color(255, 0, 0), Color(0, 255, 0));
15 graphics.FillRectangle(&hre, 10, 140, 200, 20);

四、TextureBrush

  材质画刷需要指定所应用的材质,材质以图像形式指定。代码效果如下所示:

1 Graphics graphics(dc);
2 Gdiplus::TextureBrush tba(&Image(L"F://bb.bmp"));
3 CRect crt;
4 GetClientRect(&crt);
5 graphics.FillRectangle(&tba,crt.left,crt.top,crt.Width(),crt.Height());

五、LinearGradientBrush

  路径渐变画刷可填充一个图形,通过一种颜色渐变为另一种颜色,代码效果如下所示:

 1     Graphics graphics(dc);
 2     
 3     CRect crt;
 4     GetClientRect(&crt);
 5     Gdiplus::LinearGradientBrush lbr(Gdiplus::Rect(crt.left,crt.top,crt.Width()/2,crt.Height()),
 6                                     Color(0,0,255),Color(0,255,0),Gdiplus::LinearGradientMode::LinearGradientModeHorizontal);
 7     graphics.FillRectangle(&lbr,crt.left,crt.top,crt.Width()/2,crt.Height());
 8 
 9     Gdiplus::LinearGradientBrush lbra(Gdiplus::Rect(crt.left, crt.top, crt.Width() / 2, crt.Height()),
10                                     Color(0, 0, 255), Color(0, 255, 0),Gdiplus::LinearGradientMode::LinearGradientModeVertical);
11     graphics.FillRectangle(&lbra, crt.Width() / 2, crt.top, crt.Width() / 2, crt.Height());