画像を切り分ける

Bitmap の Graphics を取得して画像を切り分けます。

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

プロジェクトの設定

  1. Sprite を切り替える では Paint のときに描画する範囲(矩形で設定)を切り替えました。
    今回は大きな画像を切り分けて Bitmap[] の配列に格納します。
    girl が元の大きな画像を読み込む領域です。
    ページ先頭の画像(girl.gif) を c:\data\test\ に格納しておいて下さい。
    sp_girl[] が7枚の画像に切り分けて、格納する領域です。
        Bitmap      girl;
        Bitmap[]    sp_girl = new Bitmap[7];
    
    画像の切り分けには、前回と同じ DrawImage() メソッドを使うのですが、このとき sp_girl[] の Graphics が必要になります。
    Graphics とは Windows の HDC(デバイスコンテキストのハンドル)で、これを使って Bitmap に対して描画を行います。
    Rectangle(0,0,128,216) が受取側(sp_girl 配列)の矩形で、Rectangle(128*i,0,128,216) が送り側(girl) の矩形です。
            for(int i=0; i<7; i++)
            {   sp_girl[i] = new Bitmap(128,216);
                graphics = Graphics.FromImage(sp_girl[i]);
                graphics.DrawImage(girl,new Rectangle(0,0,128,216),
                    new Rectangle(128*i,0,128,216),GraphicsUnit.Pixel);
            }
    
  2. 7枚の画像の切り分けが終われば、マウスのクリックで順番に切り替えながらアニメーションします。
        private void OnMyMouseDown(object sender, MouseEventArgs e)
        {
            SP_NO= (SP_NO+1)%7;
            Invalidate();
        }
    
  3. 全ソースコードです。
    /************************************************/
    /*★ Graphics を取得して画像を分割    前田 稔 ★*/
    /************************************************/
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    class MyForm : Form
    {
        Bitmap      girl;
        Bitmap[]    sp_girl = new Bitmap[7];
        Graphics    graphics;
        int         SP_NO;
    
        public MyForm()
        {
            try
            {   girl = new Bitmap("c:\\data\\test\\girl.gif");  }
            catch
            {   MessageBox.Show("画像ファイルが読めません!");
                return ;
            }
    
            for(int i=0; i<7; i++)
            {   sp_girl[i] = new Bitmap(128,216);
                graphics = Graphics.FromImage(sp_girl[i]);
                graphics.DrawImage(girl,new Rectangle(0,0,128,216),
                    new Rectangle(128*i,0,128,216),GraphicsUnit.Pixel);
            }
            Paint += new PaintEventHandler(MyHandler);
            MouseDown += new MouseEventHandler(OnMyMouseDown);
            SP_NO = 0;
        }
    
        private void MyHandler(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawImage(sp_girl[SP_NO], 60, 20);
        }
    
        private void OnMyMouseDown(object sender, MouseEventArgs e)
        {
            SP_NO= (SP_NO+1)%7;
            Invalidate();
        }
    }
    
    class form01
    {   public static void Main()
        {   MyForm mf = new MyForm();
            Application.Run(mf);
        }
    }
    

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