将mouseUp事件上创建的图形值传输或复制到Paint事件

时间:2010-08-19 23:34:24

标签: c# list gdi+

如何将我创建的图形代码放在绘画事件上? 我在绘画时遇到了麻烦。我试图将Points添加到List中,但我绘制的线条正在合并。 救命啊!

以下是代码:

private Point _ps = new Point();
private Point _pe = new Point();
private TransparentPanel _thispan;
private Rectangle _SelectRect;
private Graphics _g;
private Pen _pen;
List<Point> _listPS = new List<Point>();
List<Point> _listPE = new List<Point>();

private void _newTransPan_MouseDown(object sender, MouseEventArgs e)
{
    _SelectRect.Width = 0;
    _SelectRect.Height = 0;
    _SelectRect.X = e.X;
    _SelectRect.Y = e.Y;

    _ps.X = e.X;
    _ps.Y = e.Y;
    _pe = _ps;
}

private void _newTransPan_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _thispan = (TransparentPanel)sender;

        ControlPaint.DrawReversibleLine(_thispan.PointToScreen(_ps),  _thispan.PointToScreen(_pe), Color.Red);
        _pe = new Point(e.X, e.Y);
        ControlPaint.DrawReversibleLine(_thispan.PointToScreen(_ps), _thispan.PointToScreen(_pe), Color.Red);
    }
}

private void _newTransPan_MouseUp(object sender, MouseEventArgs e)
{

    _thispan = (TransparentPanel)sender;

    _g = _thispan.CreateGraphics();
    _flagCol = _mdt._getColorVal();
    _pen = new Pen(_flagCol, _mdt._getPenVal());
    _pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
    _pen.DashCap = System.Drawing.Drawing2D.DashCap.Triangle;
    ControlPaint.DrawReversibleLine(_thispan.PointToScreen(_ps), _thispan.PointToScreen(_pe), Color.Red);
     _g.DrawLine(_pen, _ps, _pe);

     _listPS.Add(_ps);
     _listPE.Add(_pe);

 }

private void _newTransPan_Paint(object sender, PaintEventArgs e)
{
    _thispan = (TransparentPanel)sender;
    _g = _thispan.CreateGraphics();

    foreach (Point _tps in _listPS)
    {
        foreach (Point _tpe in _listPE)
        {
           _g.DrawLine(_pen, _tps, _tpe);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

_newTransPan_Paint事件处理程序中,您将每个起点与每个结束点连接起来。当然,这不会产生连续的分段线;它会产生一个涂鸦。您希望仅将每个起始点与对应的端点连接起来:

private void _newTransPan_Paint(object sender, PaintEventArgs e)
{
    var g = _newTransPan.CreateGraphics();

    for (int i = 0; i < _listPS.Count; i++)
        g.DrawLine(_pen, _listPS[i], _listPE[i]);
}

我再次强调你应该使用局部变量。如果不这样做,创建自己难以发现的错误。存在局部变量的原因;尽可能使用它们,并且只在需要时使用字段。在您的代码中:

  • _g_pen应该是局部变量。您在每种方法中为它们分配一个新值,因此没有数据共享。

  • 如果我没弄错,您的面板已经有_newTransPan,因此_thispan是多余的。您可以将其完全删除,并使用_newTransPan替换所有匹配项。