LoginSignup
2
0

More than 1 year has passed since last update.

【C#】PictureBoxにマウスで線を引く【ペイント】

Last updated at Posted at 2022-09-15

特にBitmapやGraphicsの使い方など、見返すとき用。

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace ImageEditing
    {
        public partial class frmPaintTool : Form
        {
            //変数
            Bitmap _newBitMap;              //ビットマップ画像
            bool _mouseDrug;                //マウスクリック中のフラグ
            int _prevX;                     //前のマウスカーソルのX座標
            int _prevY;                     //前のマウスカーソルのY座標
    
            public frmPaintTool()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                //BitMapオブジェクトを生成する
                _newBitMap = new Bitmap(DrawingPicBox.Width, DrawingPicBox.Height);
            }
    
    
            private void DrawingPicBox_MouseDown(object sender, MouseEventArgs e)
            {
                //マウスクリック開始判定
                _mouseDrug = true;
                //マウスカーソル位置記憶の初期化
                _prevX = e.Location.X;
                _prevY = e.Location.Y;
            }
    
            private void DrawingPicBox_MouseUp(object sender, MouseEventArgs e)
            {
                //マウスクリック終了判定
                _mouseDrug = false;
            }
    
            private void DrawingPicBox_MouseMove(object sender, MouseEventArgs e)
            {
                //マウスクリック中に、BitMapにGraphicsオブジェクトで描画する
                if (_mouseDrug == true)
                {
                    //BitMapからGraphicsオブジェクトを生成
                    Graphics objGrp = Graphics.FromImage(_newBitMap);
                    //描画に利用するペンの色、太さを設定
                    Pen objPen = new Pen(Color.Black, 3);
                    //指定したペンでマウスの位置に線を引く
                    objGrp.DrawLine(objPen, _prevX, _prevY, e.Location.X, e.Location.Y);
                    _prevX = e.Location.X;
                    _prevY = e.Location.Y;
                    objPen.Dispose();
    
                    //BitMapオブジェクトをPictureBoxに表示する
                    objGrp.Dispose();
                    DrawingPicBox.Image = _newBitMap;
                }
            }
        }
    }

Animation.gif
PictureBoxはプロパティで背景色を白色に変更

PictureBoxのMouseDownイベントで、マウスのクリックを検知
PictureBoxのMouseUpイベントで、マウスのクリック解除を検知
PictureBoxのMouseMoveイベントで、線を引く処理を呼び出す(マウスクリック中のみ)

線を描くにはDrawLine()を使用する
クリック中にマウスがPictureBoxの上で動いたら、そのマウスの位置に線を描画し、それをPictureBoxに表示する

参考にしたサイトです

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0