如何选择绘制线并将其删除C#?

时间:2014-08-08 05:33:01

标签: c# winforms

我使用DrawLine和PaintEvent画了一条简单的线。 我想选择该行并将其从世界中删除!! 我想要指导和方向,我将如何选择和删除绘制的线?

编辑: 我不需要代码。我需要一些指导和指导。所以停止杀死我的声誉:(

2 个答案:

答案 0 :(得分:0)

您无法选择它。它只是像素。您必须重新绘制绘制该线的整个区域,但现在只是不在Paint事件处理程序中绘制此行。计算必须重绘的rect并调用Control的Invalidate()方法重绘这个区域。

简单示例:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace TestPaintApp
{
    public class TestPaint : Form
    {
        private bool drawLine = false;
        private Point lineStart;
        private Point lineEnd;

        public TestPaint()
        {
            var drawLineButton = new Button();
            drawLineButton.Text = "Draw line";
            drawLineButton.Location = new Point(5, 5);
            drawLineButton.Click += DrawLineButton_Click;

            var dontDrawLineButton = new Button();
            dontDrawLineButton.Text = "Don't draw";
            dontDrawLineButton.Location = new Point(5, 30);
            dontDrawLineButton.Click += DontDrawLineButton_Click;

            GetLineRect();

            this.Controls.Add(drawLineButton);
            this.Controls.Add(dontDrawLineButton);

            this.MinimumSize = new Size(200, 200);

            this.Paint += Form_Paint;
            this.Resize += Control_Resize;
        }

        private Rectangle GetLineRect()
        {
            this.lineStart = new Point(75, 75);
            this.lineEnd = new Point(this.ClientSize.Width - 75, this.ClientSize.Height - 75);

            return new Rectangle(
                Math.Min(lineStart.X, lineEnd.X),
                Math.Min(lineStart.Y, lineEnd.Y),
                Math.Max(lineStart.X, lineEnd.X),
                Math.Max(lineStart.Y, lineEnd.Y)
                );
        }

        private void Form_Paint(object sender, PaintEventArgs e)
        {
            if (drawLine)
            {
                e.Graphics.DrawLine(Pens.Red, lineStart, lineEnd);
            }
        }

        private void Control_Resize(object sender, EventArgs e)
        {
            this.Invalidate(GetLineRect());
        }

        private void DrawLineButton_Click(object sender, EventArgs e)
        {
            drawLine = true;
            this.Invalidate(GetLineRect());
        }

        private void DontDrawLineButton_Click(object sender, EventArgs e)
        {
            drawLine = false;
            this.Invalidate(GetLineRect());
        }
    }
}

答案 1 :(得分:0)

我不是C#专家,但我可以在这里提出一些建议,首先你需要通过使用像数组这样的集合来跟踪你绘制的所有行。现在,在鼠标事件中,您需要检查水龙头是否更接近您绘制的任何线条,具体取决于您可以从集合中选择线条并重新绘制/移动或擦除。我在iOS中做了同样的事情。

请在以下链接中查看更多相关信息

Graphic - DrawLine - draw line and move it - >非常接近你所要求的。

How to draw a selectable line?

How to draw and move shapes using mouse in C#

希望这会有所帮助

-anoop