How to delete a drawn line on a form?

僤鯓⒐⒋嵵緔 提交于 2019-12-11 14:10:25

问题


Actually there are some similar questions about this topic but I couldn't see the answer what I am looking for.

For example I have drawn 2 lines on windows form and I want to delete one of them and keep the other, how can I do that?

this.Invalidate(); or Graphics.Clear(); clear all the form, I don't want this, I want to delete specific line. Do you have any other solutions?


回答1:


The following will delete the all created lines in reverse chronological sequence.

    Graphics g;
    Pen p;
    Bitmap bmp;
    List<Point> Lines = new List<Point>();

    private void Form2_Load(object sender, EventArgs e)
    {
        bmp = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        BackgroundImage = bmp;
        g = Graphics.FromImage(BackgroundImage);
        g.Clear(Color.DeepSkyBlue); //This is our backcolor
    }

    private void btnLine1_Click(object sender, EventArgs e)
    {
        Point A = new Point(50, 50);
        Point B = new Point(100, 50);
        p = new Pen(Color.Red);
        g.DrawLine(p, A, B); //Use whatever method to draw your line
        Lines.Add(A); //Grab the first point; add to list
        Lines.Add(B); //Grab the second point; add to list
        Refresh(); //Refresh drawing to bitmap.
    }

    private void btnDrawLine2_Click(object sender, EventArgs e)
    {
        Point A = new Point(50, 60);
        Point B = new Point(100, 60);
        p = new Pen(Color.White);
        g.DrawLine(p, A, B); //Same logic as above
        Lines.Add(A);
        Lines.Add(B);
        Refresh();
    }

    private void btnUndo_Click(object sender, EventArgs e)
    {
        c = new Pen(Color.DeepSkyBlue);
        r = new Pen(lastColor.ElementAt(lastColor.Count - 2));
        try
        {
            g.DrawLine(c, Lines.ElementAt(Lines.Count - 2), Lines.ElementAt(Lines.Count - 1));
            Lines.RemoveAt(Lines.Count - 2);
            Lines.RemoveAt(Lines.Count - 1);
            for (int i = Lines.Count; i > 0; i--)
            {
            g.DrawLine(r, Lines.ElementAt(Lines.Count - 2), Lines.ElementAt(Lines.Count - 1));
            }
        }
        catch { }
        Refresh();
    }

Here's 2 lines side by side:

Here's 2 lines overlapping:

*Remember to dispose your graphics objects!



来源:https://stackoverflow.com/questions/37908570/how-to-delete-a-drawn-line-on-a-form

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