Graphicsオブジェクト
ウインドウの内部を表示したり描き直したりする必要が生ずると、Formに「Paint」というイベントが発生し、Paintプロパティに設定されているメソッドが呼び出されるようになっています。
このPaintイベント用のメソッドは、これまでのクリック時のイベント用メソッドなどとは微妙に違いがあります。これは以下のように定義されます。
private void メソッド名 (object sender, PaintEventArgs e)
{
……ここに描画処理を書く……
}
第1引数に、イベントが発生したオブジェクトが渡されるのは同じですが、第2引数に渡されるのはSystem.Windows.Formsパッケージの「PaintEventArgs」というクラスのインスタンスです。これは、描画のためのイベント情報を管理するもので、描画に必要なオブジェクトなどもこの中にまとめられているのです。
中でも重要なのが「Graphics」というオブジェクトです。これはSystem.Drawingパッケージに用意されているクラスで、これはGDI+(Graphics Device Interfaceというグラフィック描画のための機能の強化版)を利用して画面にさまざまな描画を行うための機能を提供します。
Paintイベント
フォームのプロパティをイベントに切り替えて、Paintイベントを探し、メソッド名Form1Paintを入力
Paintイベントで渡されるPaintEventArgsインスタンスから以下のようにして取り出します。
Graphics 変数 = 《PaintEventArgs》.Graphics;
Penと図形の描画
- g.DrawLine(p,75,75,50,50); // 直線
- g.DrawEllipse(p,75,75,50,50); // 円
private void Form1Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen p = new Pen(Color.Red); // Penインスタンスの作成
g.DrawEllipse(p,75,75,50,50);
}
Penと多角形を描く
private void Form1Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen p = new Pen(Color.Red); // Penインスタンスの作成
Brush b = new SolidBrush(Color.Blue); // Brushインスタンスの作成
//直線で接続する点の配列を作成
Point[] ps = {new Point(100, 0),
new Point(158, 180),
new Point(4, 69),
new
Point(195,
69),
new Point(41, 180)};
//多角形を描画する
g.DrawPolygon(p, ps);
}
Brushと塗りつぶし図形
private void Form1Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Brush b = new SolidBrush(Color.Blue); // Brushインスタンスの作成
g.DrawEllipse(p,75,75,50,50);
}
実例
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MyFrmApp
{
public class MyForm : Form
{
public MyForm()
{
this.Width = 300;
this.Height = 200;
this.Paint += myframe_paint;
}
private void Form1Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen p = new Pen(Color.Red); // Penインスタンスの作成
Brush b = new SolidBrush(Color.Blue); // Brushインスタンスの作成
g.FillRectangle(b,50,50,50,50);
g.DrawEllipse(p,75,75,50,50);
//直線で接続する点の配列を作成
Point[] ps = {new Point(0, 0),
new Point(150, 50),
new Point(80, 100),
new Point(100, 150)};
//多角形を描画する
g.DrawPolygon(p, ps);
}
}
}
演習
五芒星を描く
***
五芒星(ごぼうせい、英: pentagram)または五芒星形・五角星形・五線星型・星型五角形・正5/2角形は、互いに交差する、長さの等しい5本の線分から構成される図形で星型正多角形の一種である。 正五角形に内接し、対称的である。 一筆書きが可能。
参考
- http://qiita.com/tomato360/items/a59f2ee4df4fd2f24227





