PictureBox の画像の上から図形を描く

ToolBox を使わずに PictureBox を貼り付けて、PaintHandler で画像の上から図形を描きます。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. PictureBox を貼り付けて画像を描画する簡単な方法は PictureBox に画像を描く を参照して下さい。
    今回は ToolBox を使わずに、直接プログラムで [PictureBox] を貼り付けます。
    従って、空のプロジェクトを作成して、下記のプログラムをプロジェクトに組み込んで下さい。
    自動生成を使って Form を作成 の場合も同じ要領です。
  2. img が PictureBox に表示する画像ファイルです。
    テストするときは、PictureBox のサイズに合わせて適当な画像を調達して下さい。
    画像ファイルの名前をフルパスで指定します。
        Image   img = Image.FromFile(@"C:\Data\Test\Kishi.gif");
        
  3. pictureBox.Paint に PictureBox に描画する EventHandler を設定します。
    pictureBox1.Image に背景として描画する画像を設定します。
        pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(PictureBox1_Paint);
        pictureBox1.Image = img;
        
  4. PictureBox の背景画像の上から図形を描画する EventHandler です。
    Graphics g とはウインドウに描画するためのハンドル(デバイスコンテキスト)のようなものでしょうか?
        private void PictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics g = e.Graphics;
    
            g.DrawRectangle(new Pen(Color.Red, 3f), new Rectangle(30, 20, 200, 30));
            g.DrawEllipse(new Pen(Color.Blue), new Rectangle(50, 80, 160, 60));
        }
        
  5. 次の行をコメントアウトすると、画像の描画が消えて図形だけになるので、試してみて下さい。
        //Image   img = Image.FromFile(@"C:\Data\Test\Kishi.gif");
        //pictureBox1.Image = img;
        
  6. ソースコードです。
    /***********************************************************************/
    /*★ PictureBox の画像の上から、PaintHandler で図形を描く    前田 稔 ★*/
    /***********************************************************************/
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    public class MyForm : Form
    {
        private PictureBox pictureBox1;
        Image   img = Image.FromFile(@"C:\Data\Test\Kishi.gif");
    
        public MyForm()
        {
            // pictureBox1
            pictureBox1 = new System.Windows.Forms.PictureBox();
            pictureBox1.Location = new Point(12, 12);
            pictureBox1.Size = new Size(258, 232);
            pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(PictureBox1_Paint);
            pictureBox1.Image = img;
    
            // MyForm
            Controls.Add(pictureBox1);
    
        }
    
        private void PictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics g = e.Graphics;
    
            g.DrawRectangle(new Pen(Color.Red, 3f), new Rectangle(30, 20, 200, 30));
            g.DrawEllipse(new Pen(Color.Blue), new Rectangle(50, 80, 160, 60));
        }
    }
    
    class form01
    {
        public static void Main()
        {
            MyForm mf = new MyForm();
            Application.Run(mf);
        }
    }
    

超初心者のプログラム入門(C# Frame Work)