Draw lines on a PictureBox

前端 未结 3 1294
慢半拍i
慢半拍i 2021-01-13 23:01

My question is related to Stack Overflow question Draw lines on a picturebox using mouse clicks in C#, but when the mouse button is up, the drawn line disappears. H

3条回答
  •  迷失自我
    2021-01-13 23:35

    Here is a small complete program that does draw lines based on points (in this case, it follows the mouse). I think you can rework that into what you need.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
    
        // Variable that will hold the point from which to draw the next line
        Point latestPoint;
    
    
        private void GainBox_MouseDown(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                // Remember the location where the button was pressed
                latestPoint = e.Location;
            }
        }
    
        private void GainBox_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                using (Graphics g = GainBox.CreateGraphics())
                {
                    // Draw next line and...
                    g.DrawLine(Pens.Red, latestPoint, e.Location);
    
                    // ... Remember the location
                    latestPoint = e.Location;
                }
            }
        }
    }
    

    One problem in your solution is that you are drawing on a temporary bitmap, but the image in that bitmap is never transferred to your PictureBox. In the solution presented here, there isn't any extra bitmap needed.

提交回复
热议问题