Draw lines on a PictureBox

烈酒焚心 提交于 2020-02-02 04:08:13

问题


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. How do I fix this?

private void GainBox_MouseDn(object sender, MouseEventArgs e)
{
    mouse_dn = true;
}

private void GainBox_MouseMv(object sender, MouseEventArgs e)
{
    //Line drawn from lookup table
    if (mouse_dn)
    {
        img = new Bitmap(256, 256);

        //Get the coordinates (x, y) for line from lookup table.

        for (x = x1; x < x2; x++)
            img.SetPixel(x, y, Color.Red);

        //Same for y coordinate
    }
    GainBox.Refresh();
}

private void GainBox_MouseUp(object sender, MouseEventArgs e)
{
    mouse_dn = false;
}

回答1:


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.




回答2:


gainbox.refresh() should stay inside the if (mouse_dn) clause.




回答3:


Use Graphics Object to Drawline

e.g.

Graphics gfx = GainBox.CreateGraphics();
gfx.Drawline([Your Parameters here]);


来源:https://stackoverflow.com/questions/4266745/draw-lines-on-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!