c# - 在 WPF 中绘制数千个矩形

标签 c# wpf canvas itemscontrol

我需要绘制许多矩形(~50000)。目前我正在使用以下方法。

<ItemsControl ItemsSource="{Binding Elements}" IsHitTestVisible="False"  Background="Transparent">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas IsItemsHost="True"
                    Background="Transparent"
                    Width="500" 
                    Height="500">
            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Bottom" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>

    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type models:Element}">
            <Rectangle Width  = "{Binding Width}"
                       Height = "{Binding Height}"
                       Fill= "{Binding Brush}"
                       SnapsToDevicePixels="True" >
            </Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

问题是绘制这么多矩形需要很长时间。 有没有更好的方法来绘制大量形状?

最佳答案

Wpf 的渲染引擎效率很低,50000 个形状对它来说太多了,即使没有绑定(bind)开销也是如此。

快速浏览一下这份文件:WPF rendering system

相反,请考虑使用绘图 API,例如 Direct2D,它可以比较好地从 WPF 访问:Direct2D with WPF

关于c# - 在 WPF 中绘制数千个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22812919/

相关文章:

c# - .NET 库中是否有 Month 的预定义枚举?

c# - 我可以将 IFormatProvider 与 WPF 绑定(bind)一起使用到自定义类型吗?

c# - 使用 MVVM 的 WPF 脚手架?

Java Canvas repaint() 闪烁

c# - 相当于 Xamarin Forms 的 Toast

c# - 如何进行异地/云文件同步

c# - 在 C# 中将 COM 对象作为参数传递

wpf - 保存 WPF 窗口和位置

javascript - 如何在createjs中屏蔽视频

php - 如何使用 heatmap.js 保存 canvas 标签生成的图像文件?