ディスプレイ デバイスにグラフィックスを描画するには、Graphics オブジェクトが必要です。Graphics オブジェクトは、通常は Form オブジェクトのクライアント領域である描画面に関連付けられます。次のいずれかの方法を使用して、Graphics オブジェクトを取得し、Form に対して描画します。
CreateGraphics メソッドの使用
Form.CreateGraphics メソッドを使用して、Form オブジェクトに対して描画を行う Graphics オブジェクトを作成します。
Form クラスのサブクラスを作成し、そのサブクラスに対して CreateGraphics メソッドを呼び出し、結果として得られる Graphics オブジェクトを使用してフォームのクライアント領域に四角形を描画する例を次に示します。
Imports System
Imports System.Windows.Forms
Imports System.Drawing
'Create a Class that inherits from System.Windows.Forms.Form.
Class myForm
Inherits Form
'Override myForm's OnClick event.
Protected Overrides Sub OnClick(ByVal e As EventArgs)
'Use the CreateGraphics method to create a Graphics object.
Dim formGraphics As Graphics
formGraphics = Me.CreateGraphics
'Create a red brush.
Dim redBrush As new SolidBrush(Color.Red)
'Draw a rectangle on the form.
formGraphics.FillRectangle(redBrush, 0, 0, 100, 100)
End Sub 'OnClick
Public Shared Sub Main()
Application.Run(new myForm())
End Sub 'Main
End Class
[C#]
using System;
using System.Windows.Forms;
using System.Drawing;
//Create a Class that inherits from System.Windows.Forms.Form.
class myForm : Form {
//Override myForm's OnClick event.
protected override void OnClick(EventArgs e) {
//Use the CreateGraphics method to create a Graphics object.
Graphics formGraphics = this.CreateGraphics();
//Create a red brush.
SolidBrush redBrush = new SolidBrush(Color.Red);
//Draw a rectangle on the form.
formGraphics.FillRectangle(redBrush, 0, 0, 100, 100);
}
public static void Main() {
Application.Run(new myForm());
}
}
OnPaint イベント ハンドラのオーバーライド
Form クラスの OnPaint メソッドは、パラメータとして PaintEventArgs オブジェクトを受け取ります。このオブジェクトのメンバの 1 つに、フォームに関連付けられている Graphics オブジェクトがあります。
Form クラスの OnPaint メソッドをオーバーライドし、パラメータとして受け取った PaintEventArgs の Graphics オブジェクトを使用して、フォームのクライアント領域に四角形を描画する例を次に示します。
Imports System.Windows.Forms
Imports System.Drawing
'Create a Class that inherits from System.Windows.Forms.Form.
Class myForm
Inherits Form
'Override myForm's OnPaint event handler.
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
'Use the Graphics object from the PaintEventArgs object.
Dim formGraphics As Graphics
formGraphics = e.Graphics
'Create a red brush.
Dim redBrush As new SolidBrush(Color.Red)
'Draw a rectangle on the form.
formGraphics.FillRectangle(redBrush, 0, 0, 100, 100)
End Sub 'OnClick
Public Shared Sub Main()
Application.Run(new myForm())
End Sub 'Main
End Class
[C#]
using System;
using System.Windows.Forms;
using System.Drawing;
//Create a Class that inherits from System.Windows.Forms.Form.
class myForm : Form {
//Override myForm's OnPaint event.
protected override void OnPaint(PaintEventArgs e) {
//Get the Graphics object from the PaintEventArgs object.
Graphics formGraphics = e.CreateGraphics();
//Create a red brush.
SolidBrush redBrush = new SolidBrush(Color.Red);
//Draw a rectangle on the form.
formGraphics.FillRectangle(redBrush, 0, 0, 100, 100);
}
public static void Main() {
Application.Run(new myForm());
}
}