WPF UI交互滞后,但为什么呢?

时间:2013-01-14 23:30:56

标签: wpf lag onrender

为了演示我遇到的问题,我编写了下面绘制曲线的简单示例,以及跟随光标的黑线。

有人可以解释为什么当我增加“numPointsMul”时,与鼠标的交互和光标线的绘制会变得非常滞后吗?

为什么图中的点数会以这种方式影响指针的绘制?请注意,我已关闭所有热门测试,图表仅在OnRender中重新绘制。

我认为增加点数会导致OnRender函数花费更长时间,但我不明白为什么它会导致指针绘制滞后,因为OnRender isn'在光标移动时调用,但是在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);
        }
    }

0 个答案:

没有答案