为了演示我遇到的问题,我编写了下面的简单示例,该示例绘制了一条曲线和一条跟随光标的黑线。
有人可以解释为什么当我增加“numPointsMul”时,与鼠标的交互和光标线的绘制变得非常滞后?
为什么图形中的点数会这样影响指针的绘制呢?请注意,我已关闭所有命中测试,并且该图仅在OnRender
.
我收集到增加点数会导致OnRender
函数花费更长的时间,但我不明白为什么它会导致指针的绘制滞后,因为OnRender
当光标移动时不会被调用,而是会调用 Invalidation 事件。看起来命中测试仍在进行中?
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="800" Width="1024" WindowStartupLocation="CenterScreen">
<local:UserControl1/>
</Window>
<UserControl x:Class="WpfApplication4.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
IsEnabled="False" IsHitTestVisible="False">
<Line Name="m_line" Stroke="Black"/>
</UserControl>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
Application.Current.MainWindow.PreviewMouseMove += new MouseEventHandler(MainWindow_PreviewMouseMove);
}
void MainWindow_PreviewMouseMove(object sender, MouseEventArgs e)
{
m_line.X1 = m_line.X2 = Mouse.GetPosition(this).X;
m_line.Y1 = 0;
m_line.Y2 = ActualHeight;
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
drawingContext.DrawRectangle(Brushes.Green, null, new Rect(0, 0, ActualWidth, ActualHeight));
Pen p = new Pen(Brushes.Black, 1);
StreamGeometry streamGeometry = new StreamGeometry();
using (StreamGeometryContext geometryContext = streamGeometry.Open())
{
double numPointsMul = 1;
int count = (int)(ActualWidth * numPointsMul);
for (int i = 0; i < count; ++i)
{
double y = ActualHeight / 2 + 20 * Math.Sin(i * 0.1);
if (i == 0)
{
geometryContext.BeginFigure(new Point(i , y), true, true);
}
else
{
geometryContext.LineTo(new Point(i, y), true, true);
}
}
}
drawingContext.DrawGeometry(Brushes.Red, p, streamGeometry);
}
}