gpt4 book ai didi

wpf - 如何提高 Canvas 渲染性能?

转载 作者:行者123 更新时间:2023-12-04 02:05:54 34 4
gpt4 key购买 nike

我要画很多Shape (约 1/20 万)作为 [Canvas][2] 的 child 。我在我的 WPF 应用程序中将工作分为两部分:首先,我通过设置每个形状的属性(如边距、填充、宽度等)来创建形状,然后将形状添加为 Canvas 的子项。

MyCanvas.Children.Add(MyShape)

现在我想提高第二部分的性能,因为当我绘制形状时,我的应用程序被阻塞了很长时间。所以我尝试使用 Dispatcher及其方法 [BeginInvoke][4] 具有不同的 [优先级][5]:只有当我使用背景优先级时,主应用程序才不会阻塞,否则应用程序将保持阻塞状态,并且在添加所有形状之前不会显示“图片”到我的 Canvas ,但如果我使用背景优先级,显然一切都会变慢。我还尝试创建一个新线程而不是使用 Dispatcher,但没有显着变化。

当我将形状添加到 Canvas 时,我该如何解决这个问题,并总体上提高我的应用程序的性能?

谢谢。

最佳答案

需要使用Visual对象而不是 Shape ;特别是,正如所建议的,DrawingVisual :可用于渲染矢量图形的视觉对象。事实上,正如 MSDN 库中所写:

DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. This class is considered lightweight because it does not provide layout, input, focus, or event handling, which improves its performance. For this reason, drawings are ideal for backgrounds and clip art.



因此,例如,要创建一个包含矩形的 DrawingVisual:
private DrawingVisual CreateDrawingVisualRectangle()
{
DrawingVisual drawingVisual = new DrawingVisual();

// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();

// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new System.Windows.Point(160, 100), new System.Windows.Size(320, 80));
drawingContext.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);

// Persist the drawing content.
drawingContext.Close();

return drawingVisual;
}

为了使用 DrawingVisual 对象,您需要为这些对象创建一个宿主容器。宿主容器对象必须从 FrameworkElement 类派生,该类提供 DrawingVisual 类所缺乏的布局和事件处理支持。当您为可视对象创建宿主容器对象时,您需要将可视对象引用存储在 VisualCollection 中。 .
public class MyVisualHost : FrameworkElement
{
// Create a collection of child visual objects.
private VisualCollection _children;

public MyVisualHost()
{
_children = new VisualCollection(this);
_children.Add(CreateDrawingVisualRectangle());

// Add the event handler for MouseLeftButtonUp.
this.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(MyVisualHost_MouseLeftButtonUp);
}
}

然后事件处理例程可以通过调用 HitTest 来实现 HitTest 。方法。该方法的 HitTestResultCallback 参数指的是一个用户定义的过程,您可以使用它来确定 HitTest 的结果操作。

关于wpf - 如何提高 Canvas 渲染性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997891/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com