C#学习笔记:GDI图形高级编程(2)——关于Brush类

来源:互联网 发布:手机淘宝差评怎么删掉 编辑:程序博客网 时间:2024/06/01 07:22

使用GDI图形接口进行绘图时,如果需要填充图形,那么就需要创建一个画刷(Brush)对象。GDI的Brush类本身是抽象类,不能直接实例化,所以GDI API 提供了一下五个类,来扩展Brush,并提供了具体的实现,如下:


下面将给出几个简单的例子来说明其用法并展示使用效果。

1、SolidBrush类

1)代码片段

Graphics g=this.CreateGraphics();
Brush brush=new SolidBrush(Color.FromArgb(0,255,0));//设置画刷的颜色为绿色
g.FillEllipse(brush,100,100,200,200)//画一个椭圆,并用红色填充
(2)运行效果

2、TextureBrush类

(1)代码片段

Graphics g=this.CreateGraphics();
Bitmap map=new Bitmap("001.jpg");//载入一张图片
Brush brush=new TexureBrush(map);//创建一个文理画刷
g.FillRectangle(brush, 0, 0, 800, 500);//用图片文理填充矩形
(2)运行效果



(3)TextureBrush构造函数的其他重载

TextureBrush类的构造方法有7种重载,上面是最常用的一种,还有一种也比较常用,那就是

TextureBrush(Image bitmap,Rectangle rect),该构造方法的作用就是用矩形截取图片的一部分作为画刷。下面是例子:

Graphics g=new CreateGraphics();
Bitmap map=new Bitmap("001.jpg");
Rectangle rect=new Rectangle(0,0,200,200);//创建一个矩形结构
Brush brush=new TextureBrush(map,rect);//用矩形来截取图片的一部分作为填充文理
g.FillRectangle(brush,0,0,800,500);

运行的效果如下:


3、LinearGradientBrush类

使用LinearGradientBrush类还需引用名称空间:

Using System.Drawing.Drawing2D

(1)代码片段

LinearGradientBrush类的构造方法有8个,下面将使用由点到点的渐变画刷。

该重载的原型是LinearGradientBrush(PointF point1,PointF point2,Color color1,Color color2),前两个参数表示从点一到点二进行渐变,后两个参数表示从颜色一渐变到颜色二。下面是例子:

Graphics g=this.CreateGraphics();
PointF p1=new PointF(0,0);//p1点在(0,0)处
PointF p2=new PointF(800,500);//p2点在(800,500)处
Color  c1=Color.FromArgb(255,0,0);
Color  c2=Color.FromArgb(0,255,0);
Brush=new LinearGradientBrush(p1,p2,c1,c2);
g.FillRectangle(brush,0,0,800,500);
(2)运行效果



4、PathGradientBrush类

使用该类也要引用名称空间:

Using System.Drawing.Drawing2D
(1)代码片段

该类的构造方法也有几个重载,下面是其中的一个。

Graphics g=this.CreateGraphics();
Point[] points=new Point[4];//生成路径的顶点
points[0] = new Point(10, 10);points[1] = new Point(200, 50);points[2] = new Point(250, 150);points[3] = new Point(200, 250);
Color[] colors = new Color[4];//路径各顶点的颜色colors[0] = Color.FromArgb(255, 0, 0);colors[1] = Color.FromArgb(255, 255, 0);colors[2] = Color.FromArgb(255, 0, 255);colors[3] = Color.FromArgb(0, 0, 255);
PathGradientBrush brush=new PathGradientBrush(pionts);//将路径的顶点传给画刷
brush.CenterPoint=new Point(200,150);//设定图形的中心点
brush.SurroundColors = colors;//设定图形轮廓各顶点的颜色
g.FillPolygon(brush, points);//填充多边形
(2)运行的效果



5、HatchBrush类

引用名称空间:

Using System.Drawing.Drawing2D
(1)代码片段

Graphics g=this.CreateGraphics();
HatchBrush brush=new HatchBrush(HatchStyle.DashedDownwardDiagonal,Color.FromArgb(255,0,0));
//第一个参数是图案的类型,只能从HatchStyle里面去选
g.FillRectangle(brush, 0, 0, 500, 200);
(2)运行效果




原创粉丝点击