How to: Use Clipping with a Region

One of the properties of the Graphics class is the clip region. All drawing done by a given Graphics object is restricted to the clip region of that Graphics object. You can set the clip region by calling the SetClip method.

The following example constructs a path that consists of a single polygon. Then the code constructs a region, based on that path. The region is passed to the SetClip method of a Graphics object, and then two strings are drawn.

The following illustration shows the clipped strings.

Clip
     // 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));

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of PaintEventHandler.

Concepts

Other Resources

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft