C# to draw a point on the PictureBox control

C# to draw a point on the PictureBox control

How to realize that a point will be drawn every time the mouse is left clicked on the PictureBox control? Two methods are summarized here.
First insert a PictureBox control and a Button button on the form. When the button is clicked, the mouse enters the PictureBox control, and a point is drawn with each left click.
The first method:
using GDI+, the code is as follows:

        private string sType;//用来记录button的Name

        private void btnDrawPoint_Click(object sender, EventArgs e)
        {
    
    
            sType = "btnDrawPoint";//获取button的Name
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
    
    
            Graphics g = pictureBox1.CreateGraphics();//创建一个画板
            if (sType == "btnDrawPoint")
            {
    
    
                if (e.Button == MouseButtons.Left)
                {
    
    
                    g.FillEllipse(Brushes.Red, e.X, e.Y, 4, 4);
                }
            }
        }

The second method:
call the SetPixel method in the gdi32.dll library, the code is as follows:

        [DllImport("gdi32.dll")]
        private static extern int SetPixel(IntPtr hdc, int x1, int y1, int color);

        private string sType;//用来记录button的Name

        private void btnDrawPoint_Click(object sender, EventArgs e)
        {
    
    
            sType = "btnDrawPoint";//获取button的Name
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
    
    
            Graphics g = pictureBox1.CreateGraphics();//创建一个画板
            PointF p = new PointF(e.X, e.Y);//实例化一个点,这个点的坐标就是鼠标的x,y

            if (sType == "btnDrawPoint")
            {
    
    
                if (e.Button == MouseButtons.Left)
                {
    
    
                    DrawPoint(g, p);//调用画点的方法,把相应参数传入
                }
            }
        }

        public void DrawPoint(Graphics g, PointF p)
        {
    
    
            IntPtr hdc = g.GetHdc();

            int color = 255;//这里定义了一个整型的颜色变量,255为红色

            SetPixel(hdc, (int)p.X, (int)p.Y, color);
            g.ReleaseHdc();
        }

The second method draws very small points, and you have to look carefully to see it. Therefore, it is not recommended to use the second method to draw points. The first method is convenient and the points drawn are obvious.

Guess you like

Origin blog.csdn.net/Kevin_Sun777/article/details/108265316