方法: 領域でクリッピングを使用する

Graphics クラスのプロパティの 1 つは、クリップ領域です。 ある Graphics オブジェクトで行われるすべての描画は、その Graphics オブジェクトのクリップ領域に制限されます。 クリップ領域を設定するには、SetClip メソッドを呼び出します。

次の例では、1 つの多角形で構成されたパスを構築します。 次に、このコードにより、そのパスに基づいて領域が構築されます。 領域は Graphics オブジェクトの SetClip メソッドに渡され、2 つの文字列が描画されます。

次の図は、クリップされた文字列を示しています。

Screenshot that shows clipped strings.

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

コードのコンパイル

前の例は、Windows フォームで使用するために設計されていて、PaintEventHandler のパラメーターである PaintEventArgse を必要とします。

関連項目