如何:对区域使用剪辑

更新:2007 年 11 月

Graphics 类的一个属性是剪辑区域。所有由给定的 Graphics 对象进行的绘制都限制在 Graphics 对象的剪辑区域中。可通过调用 SetClip 方法设置剪辑区域。

示例

下面的示例构造由一个多边形组成的路径。然后,该代码根据该路径构造一个区域。将该区域传递给 Graphics 对象的 SetClip 方法,然后绘制两个字符串。

下面的插图显示这个经剪辑的字符串。

剪辑

' Create a path that consists of a single polygon.
Dim polyPoints As Point() = { _
   New Point(10, 10), _
   New Point(150, 10), _
   New Point(100, 75), _
   New Point(100, 150)}
Dim path As New GraphicsPath()
path.AddPolygon(polyPoints)

' Construct a region based on the path.
Dim [region] As New [Region](path)

' Draw the outline of the region.
Dim pen As Pen = Pens.Black
e.Graphics.DrawPath(pen, path)

' Set the clipping region of the Graphics object.
e.Graphics.SetClip([region], CombineMode.Replace)

' Draw some clipped strings.
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
   fontFamily, _
   36, _
   FontStyle.Bold, _
   GraphicsUnit.Pixel)
Dim solidBrush As New SolidBrush(Color.FromArgb(255, 255, 0, 0))

e.Graphics.DrawString( _
   "A Clipping Region", _
   font, _
   solidBrush, _
   New PointF(15, 25))

e.Graphics.DrawString( _
   "A Clipping Region", _
   font, _
   solidBrush, _
   New PointF(15, 68))

     // Create a path that consists of a single polygon.
     Point[] polyPoints = {
new Point(10, 10),
new Point(150, 10), 
new Point(100, 75),
new Point(100, 150)};
     GraphicsPath path = new GraphicsPath();
     path.AddPolygon(polyPoints);

     // Construct a region based on the path.
     Region region = new Region(path);

     // Draw the outline of the region.
     Pen pen = Pens.Black;
     e.Graphics.DrawPath(pen, path);

     // Set the clipping region of the Graphics object.
     e.Graphics.SetClip(region, CombineMode.Replace);

     // Draw some clipped strings.
     FontFamily fontFamily = new FontFamily("Arial");
     Font font = new Font(
        fontFamily,
        36, FontStyle.Bold,
        GraphicsUnit.Pixel);
     SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0));

     e.Graphics.DrawString(
        "A Clipping Region",
        font, solidBrush,
        new PointF(15, 25));

     e.Graphics.DrawString(
        "A Clipping Region",
        font,
        solidBrush,
        new PointF(15, 68));

编译代码

前面的示例是为使用 Windows 窗体而设计的,它需要 PaintEventHandler 的参数 PaintEventArgse。

请参见

概念

GDI+ 中的区域

其他资源

使用区域