WPF MouseMove InvalidateVisual OnRender更新非常慢

pm1*_*101 4 c# wpf drawingcontext uielement

我没有在Google或Stack Overflow上找到任何有用的东西,或者根本没有答案(或者也许我只是不知道要搜索什么)-我能找到的最接近的问题是:在性能低下的原因WPF

但是我想在这个简单的程序中解决这个滞后的原因,也许我只是做的不好。

我正在UI元素的OnRender()中渲染大约2000个点,并且它们之间有线,实际上是在创建线图。没关系,但我想使用MouseMove平移图形。效果很好,但问题是LAG。每当我用鼠标拖动时,我都会期望平滑的更新,我认为重绘2000点并在它们之间有线是在i5 CPU上漫步。但是,即使在我家里的笔记本电脑上分辨率很低时,它的速度也非常慢。因此,我检查了性能分析器。OnRender()函数几乎不使用任何CPU。

MouseMove和OnRender几乎不占用太多CPU

事实证明,正在更改和使用大量CPU的是Layout。

布局使用最多的CPU

“版式”花费最多的时间来完成

布局花费最多的时间 它说对Visual树进行了更改-但未进行任何更改-仅调用了InvalidateVisual

现在,我听到了术语“视觉树”的话题,但是在这个简单的项目中几乎没有任何视觉效果。只是主窗口上的UI元素。而且它使用的是绘图上下文,我以为绘图上下文就像位图一样绘制,或者它是使用自己的事件/命中框等绘制UI元素的?因为我想要的只是让UIElement像图像一样工作,而且还要处理鼠标事件,所以我可以拖动整个对象(或使用鼠标滚轮缩放)。

所以问题:

  1. 如果Layout造成速度缓慢/滞后,如何防止这种情况?
  2. 我还注意到有很多垃圾收集是有意义的,但是我不希望它在渲染期间发生。我宁愿在闲置时这样做。但是如何?

来源如下:

.cs文件

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace SlowChart
{
    public class SlowChartClass : UIElement
    {
        List<Point> points = new List<Point>();

        double XAxis_Width = 2000;
        double XAxis_LeftMost = 0;

        double YAxis_Height = 300;
        double YAxis_Lowest = -150;

        Point mousePoint;
        double XAxis_LeftMostPan = 0;
        double YAxis_LowestPan = 0;

        public SlowChartClass()
        {
            for (int i = 0; i < 2000; i++)
            {
                double cos = (float)Math.Cos(((double)i / 100) * Math.PI * 2);
                cos *= 100;

                points.Add(new Point(i, cos));
            }

            MouseDown += SlowChartClass_MouseDown;
            MouseUp += SlowChartClass_MouseUp;
            MouseMove += SlowChartClass_MouseMove;
        }

        private void SlowChartClass_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (IsMouseCaptured)
            {
                XAxis_LeftMost = XAxis_LeftMostPan - (e.GetPosition(this).X - mousePoint.X);
                YAxis_Lowest = YAxis_LowestPan + (e.GetPosition(this).Y - mousePoint.Y);
                InvalidateVisual();
            }
        }

        private void SlowChartClass_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ReleaseMouseCapture();
        }

        private void SlowChartClass_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            mousePoint = e.GetPosition(this);
            XAxis_LeftMostPan = XAxis_LeftMost;
            YAxis_LowestPan = YAxis_Lowest;
            CaptureMouse();
        }

        double translateYToScreen(double Y)
        {
            double y = RenderSize.Height - (RenderSize.Height * ((Y - YAxis_Lowest) / YAxis_Height));

            return y;
        }

        double translateXToScreen(double X)
        {
            double x = (RenderSize.Width * ((X - XAxis_LeftMost) / XAxis_Width));


            return x;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            bool lastPointValid = false;
            Point lastPoint = new Point();
            Rect window = new Rect(RenderSize);
            Pen pen = new Pen(Brushes.Black, 1);

            // fill background
            drawingContext.DrawRectangle(Brushes.White, null, window);

            foreach (Point p in points)
            {
                Point screenPoint = new Point(translateXToScreen(p.X), translateYToScreen(p.Y));

                if (lastPointValid)
                {
                    // draw from last to  this one
                    drawingContext.DrawLine(pen, lastPoint, screenPoint);
                }

                lastPoint = screenPoint;
                lastPointValid = true;
            }

            // draw axis
            drawingContext.DrawText(new FormattedText(XAxis_LeftMost.ToString("0.0") + "," + YAxis_Lowest.ToString("0.0"),CultureInfo.InvariantCulture,FlowDirection.LeftToRight,new Typeface("Arial"),12,Brushes.Black),new Point(0,RenderSize.Height-12));

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.XAML文件

<Window x:Class="SlowChart.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SlowChart"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:SlowChartClass/>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

Dav*_*ske 6

不要InvalidateVisual()这样 它会触发用户界面的完全重新布局,这非常慢。

在WPF中获得良好性能的关键是要了解它是一个保留的绘图系统。OnRender()应该真正命名AccumulateDrawingObjects()。它仅在布局过程结束时使用,并且它累积的对象实际上是活动对象,您可以完成对其进行更新。


做您想做的事的有效方法是为图表创建一个DrawingGroup“ backingStore”。您的OnRender()唯一需要做的就是将backingStore添加到DrawingContext。然后,您可以随时使用backingStore.Open()对其进行更新,并将其绘制到其中。WPF将自动更新您的UI。

您会发现StreamGeometry绘制到的最快方法DrawingContext,因为它可以优化非动画几何。

您还可以通过使用获得一些额外的性能 .Freeze()在Pen上,因为它不是动画的。尽管我怀疑您仅会绘制2000点,您才会注意到。

看起来像这样:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {      
    base.OnRender(drawingContext);            

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// Call render anytime, to update visual
// without triggering layout or OnRender()
public void Render() {            
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();            
}

private void Render(DrawingContext drawingContext) {
    // move the code from your OnRender() here
} 
Run Code Online (Sandbox Code Playgroud)

如果您想查看更多示例代码,请看这里:

https://github.com/jeske/SoundLevelMonitor/blob/master/SoundLevelMonitorWPF/SoundLevelMonitor/AudioLevelsUIElement.cs#L172


但是,如果视觉效果是相对静态的,而您要做的只是平移和缩放,还有其他选择。您可以创建一个Canvas,并将其实例化为Shapes,然后在移动鼠标时将Canvas变换弄乱以平移和缩放。