在点和光标位置之间绘制线条

时间:2014-11-03 18:31:31

标签: c# winforms draw

我在这里有一个类似的问题: Drawing a line by mouse in a panel

我实际使用了列表中的第一个解决方案,取得了巨大的成功,创建了一个名为UserControl的{​​{1}}。

但是,我希望此模型由SuperPanel上的SuperPanelMouseDown以外的其他内容驱动。我希望通过调用一个公共方法将其设置为ON或OFF,该方法将由另一个控件的事件处理程序调用,如按钮......这可能吗?

到目前为止我尝试过的每一种方式都不起作用,我似乎无法理解为什么。这是我到目前为止的代码:

超级密码

MouseUp

主要Winforms事件

public partial class SuperPanel : Panel
{
    private Point _origin = Point.Empty;
    private Point _terminus = Point.Empty;
    private Boolean _draw = false;
    private List<Tuple<Point, Point>> _lines = new List<Tuple<Point, Point>>();
    public bool DrawLine {
        get { return this._draw; }
        set { this._draw = value; }
    }

    public SuperPanel()
    {
        InitializeComponent();
        Dock = DockStyle.Fill;
        DoubleBuffered = true;
    }

    public void StartDrawing(Point origin)
    {
        _draw = true;
        _origin = origin;
        _terminus = Point.Empty;
        Invalidate();
    }

    public void StopDrawing()
    {
        if (_draw && !_origin.IsEmpty && !_terminus.IsEmpty)
            _lines.Add(new Tuple<Point, Point>(_origin, _terminus));

        _draw = false;
        _origin = Point.Empty;
        _terminus = Point.Empty;
        Invalidate();
    }

    //the events on the control itself, in my mind, are no longer needed?
    //protected override void OnMouseDown(MouseEventArgs e)
    //{
    //    base.OnMouseDown(e);
    //    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    //    {
    //        _draw = true;
    //        _origin = e.Location;
    //    }
    //    else
    //    {
    //        _draw = false;
    //        _origin = Point.Empty;
    //    }

    //    _terminus = Point.Empty;
    //    Invalidate();
    //}

    //protected override void OnMouseUp(MouseEventArgs e)
    //{
    //    base.OnMouseUp(e);
    //    if (_draw && !_origin.IsEmpty && !_terminus.IsEmpty)
    //        _lines.Add(new Tuple<Point, Point>(_origin, _terminus));
    //    _draw = false;
    //    _origin = Point.Empty;
    //    _terminus = Point.Empty;
    //    Invalidate();
    //}

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        if (_draw)
            _terminus = e.Location;
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        foreach (var line in _lines)
            e.Graphics.DrawLine(Pens.Blue, line.Item1, line.Item2);
        if (!_origin.IsEmpty && !_terminus.IsEmpty)
            e.Graphics.DrawLine(Pens.Red, _origin, _terminus);
    }
}

然而,这根本不起作用。调用 void MyCtrl1_OnVectorClicked(MyToken sender, Point MyLocation) { //If we are not already tracking a token vector... if (this.ActiveToken == null) { this.ActiveToken = sender; this.ActiveSourcePoint = MyLocation; this.panel1.DrawLine = true; this.panel1.StartDrawing(MyLocation); } else { //Stop tracking the vector and stop drawing the line... } } 方法绝对没有任何意义。你能告诉我为什么吗?

0 个答案:

没有答案