使用鼠标按下、移动和向上事件绘制时折线速度问题

Polyline speed issue while drawing using mouse down, move, and up event

我在 C# WPF 中使用鼠标按下、移动和向上事件绘制折线时遇到性能问题。请看代码。我的代码工作正常。我面临的问题是,每当我想在一段时间后画一条连续的线时,线的移动就会变慢。我想知道您是否有更好的解决方案以更快的方式画线,或者是否有更好的解决方案来改进现有代码。
谢谢

Polyline freeLine;
Point _startPoint;

public void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    _startPoint = e.GetPosition(canvas);
    freeLine = new Polyline();
    freeLine.StrokeDashCap = PenLineCap.Square;
    freeLine.Stroke = color;
    freeLine.StrokeThickness = thickness;
    canvas.Children.Add(freeLine);
    freeLine.StrokeLineJoin = PenLineJoin.Round;
}

public void canvas_MouseMove(object sender, MouseButtonEventArgs e)
{
    Point currentPoint = e.GetPosition(canvas1);
    if (_startPoint != currentPoint)
    {
        arrowfreeLine.Points.Add(currentPoint1);
    }
}

public void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    freeLine = null;
}

您可以做的是通过丢弃彼此非常接近的点来减少点数。在下面的示例中,我删除了前一个 significant 点 10 个像素以内的所有点。

private Brush _color = new SolidColorBrush(Colors.Red);
private double _thickness = 4.0;
private int _previousSignificantPoint = 0;
private Polyline _freeLine;

private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    // Capture mouse
    canvas.CaptureMouse();
    Point startPoint = e.GetPosition(canvas);
    _freeLine = new Polyline
    {
        StrokeDashCap = PenLineCap.Square,
        StrokeLineJoin = PenLineJoin.Round,
        Stroke = _color,
        StrokeThickness = _thickness
    };

    // Add first point
    _freeLine.Points.Add(startPoint);

    // make it the first "significant" point
    _previousSignificantPoint = 0;

    canvas.Children.Add(_freeLine);
}

private void canvas_MouseMove(object sender, MouseEventArgs e)
{
    // Make sure the mouse is pressed and we have a polyline to work with
    if (_freeLine == null) return;
    if (e.LeftButton != MouseButtonState.Pressed) return;

    // Get previous significant point to determine distance
    Point previousPoint = _freeLine.Points[_previousSignificantPoint];
    Point currentPoint = e.GetPosition(canvas);

    // If we have a new significant point (distance > 10) remove all intermediate points
    if (Distance(currentPoint, previousPoint) > 10)
    {
        for(int i = _freeLine.Points.Count - 1; i > _previousSignificantPoint; i--)
            _freeLine.Points.RemoveAt(i);

        // and set the new point as the latest significant point
        _previousSignificantPoint = _freeLine.Points.Count;
    }

    _freeLine.Points.Add(currentPoint);
}

private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    // release mouse capture
    canvas.ReleaseMouseCapture();
    _freeLine = null;
}

private static double Distance(Point pointA, Point pointB)
{
    return Math.Sqrt(Math.Pow(pointA.X - pointB.X, 2) + Math.Pow(pointA.Y - pointB.Y, 2));
}

结果: