裁剪
规则形状的裁剪区域 Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); //Define the rectangle that we'll use to define our clipping region Rectangle rect = new Rectangle(10, 10, 80, 50); //Draw the clipping region g.DrawRectangle(Pens.Black, rect); //now apply the clipping region g.SetClip(rect); //now draw something onto the drawing surface //with the clipping region applied g.FillEllipse(Brushes.Blue, 20, 20, 100, 100); 不规则形状的裁剪区域 Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); //create a region object and make sure it's empty Region reg = new Region(); reg.MakeEmpty(); //create an irregular Region.. //..add a circle to the region GraphicsPath gp = new GraphicsPath(); gp.AddEllipse(10, 10, 50, 50); reg.Union(gp); //..add a triangle to the region gp.Reset(); gp.AddLine(40, 40, 70, 10); gp.AddLine(70, 10, 100, 40); gp.CloseFigure(); reg.Union(gp); //..add a rectangle to the region reg.Union(new Rectangle(40, 50, 60, 60)); //set the clipping region g.SetClip(reg, CombineMode.Replace); //paint the client rectangle green, //only the clipped region will be affected g.FillRectangle(Brushes.Green, this.ClientRectangle); gp.Dispose(); reg.Dispose(); 这里通过使用一些Union类型创建了一个相当复杂的Region对象,然后把此区域分配给裁剪区域(使用SetClip方法)。最后,我们把整个客户区域矩形涂上绿色。 注:开头调用Region对象的MakeEmpty方法是必要的,因为我们使用的重载的Region构造函数生成了一个Region对象,表示完整的无限大的绘图表面。但我们想做的是首先创建一个空的Region对象,然后向其中添加内容。所以,我们使用MakeEmpty来创建空的Region、 在裁剪区域使用文本 我们可以创建一个GraphicsPath对象,使用它的AddString方法,让他具有字符串中字符轮廓的形状,从而创建一个特殊的效果。然后,可以使用GraphicsPath作为裁剪区域的轮廓,最后用我们选择的任意笔画或图像来绘制裁剪的绘图表面。 Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); GraphicsPath gp = new GraphicsPath(); gp.AddString("Swirly", new FontFamily("Times New Roman"), (int)(FontStyle.Bold | FontStyle.Italic), 144, new Point(5, 5), StringFormat.GenericTypographic); //set clipping region g.SetClip(gp); //paint the client rectangle using an image. //only the clipped region will be affected g.DrawImage(new Bitmap("a.jpg"), this.ClientRectangle); gp.Dispose();
CombineMode枚举用来表示指定区域如何与现有裁剪区域结合,枚举中一共有6个值:CombineMode.Replace,CombineMode.Complement,CombineMode.Exclude,CombineMode.Intersect,CombineMode.Union,CombineMode.Xor,当传递一个Region对象给SetClip方法时,还必须同时传递一个取自CombineMode枚举的值。