在使用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;
}
答案 0 :(得分:2)
您可以做的是通过丢弃彼此非常接近的点数来减少点数。在下面的示例中,我删除了前一个重要点的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));
}
结果: