首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MouseMove InvalidateVisual OnRender更新非常慢

MouseMove InvalidateVisual OnRender更新非常慢
EN

Stack Overflow用户
提问于 2017-06-02 19:40:33
回答 1查看 1.9K关注 0票数 8

我没有在Google或Stack溢出上找到任何有用的东西,或者根本没有答案(或者我只是不知道该搜索什么) --我能找到的最接近的问题是:The reason behind slow performance in WPF

但是我想在这个简单的程序中找出这个滞后的原因,也许我只是做错了什么。

我在UI元素的OnRender()中呈现大约2000个点之间的线条,实质上创建了一个线状图。没关系,但我想用MouseMove来平移图表。这很好,但问题在于滞后。每当我用鼠标拖动时,我都会期待一个平滑的更新,我认为在它们之间重新绘制2000个点将是i5 CPU在公园里的一次散步。但这是难以置信的慢,即使在我的笔记本电脑在家里低分辨率。所以我检查了表演简介。OnRender()函数几乎不使用任何CPU。

原来是布局在改变和使用这么多的CPU。

“布局”是最耗时完成的。

现在,我已经听说过“视觉树”这个词,但是在这个简单的项目中几乎没有任何视觉效果。只是主窗口上的一个UI元素。它使用的是绘图上下文,我认为绘图上下文像位图一样绘制,还是用自己的事件/命中框等绘制UI元素?因为我想要的只是UIElement像图像一样的动作,还可以处理鼠标事件,这样我就可以拖动整个东西(或者用鼠标轮缩放)。

所以问题:

  1. 如果布局导致缓慢/滞后,如何防止这种情况发生?
  2. 我还注意到很多垃圾收集是有意义的,但我不希望在呈现过程中发生这种情况。我宁愿在它空闲的时候这样做。但是怎么做呢?

这里是源代码:

.cs文件

代码语言:javascript
运行
复制
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));

        }
    }
}

.XAML文件

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-08 04:51:38

不要打电话给InvalidateVisual()。它会触发UI的完整中继,这是非常慢的。

要想在WPF中获得良好的性能,关键在于理解它是一个保留的绘图系统。OnRender()确实应该被命名为AccumulateDrawingObjects()。它只在布局过程的末尾使用,并且它正在积累的对象实际上是在它完成后可以更新的活动对象。

做你想做的事情的有效方法是为你的图表创建一个DrawingGroup "backingStore“。您的OnRender()只需要将backingStore添加到DrawingContext中。然后,您可以通过使用backingStore.Open()并直接进入它来随时更新它。WPF将自动更新您的UI。

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

您还可以通过在钢笔上使用.Freeze()获得一些额外的性能,因为它不是动画的。虽然我怀疑当你只画2000点的时候你会注意到。

看起来是这样的:

代码语言:javascript
运行
复制
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
} 

如果您希望看到更多的示例代码,请在这里查看:

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

但是,如果视觉是相对静态的,而您想要做的只是平移和缩放,那么还有其他选项。您可以创建一个Canvas,并将形状实例化到其中,然后在鼠标移动时将画布转换为pan和缩放。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44336308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档