在 WPF/C# 中绘制矩形时自定义 SolidColorBrush 太慢

Custom SolidColorBrush too slow when drawing rectangles in WPF/C#

以下代码有效地创建了一个二维矩形网格,我的问题是当我使用自定义 SolidColorBrush 时渲染变得非常慢。

public partial class CalculatorView : UserControl
{
    /// This is how I'm creating my custom brush
    Brush myBlueBrush = new SolidColorBrush(Color.FromArgb(255, 165, 211, 246));

    public CalculatorView()
    {
        InitializeComponent();
    }

    private void buttonCalculate_Click(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < 100; i++) {
            for (int j = 0; j < 100; j++) {
                RectangleGeometry myRectangleGeometry = new RectangleGeometry();
                myRectangleGeometry.Rect = new Rect(((40 + 1) * i), ((40 + 1) * j), 40, 40);

                Path myPath = new Path();
                myPath.Fill = myBlueBrush; 
                myPath.StrokeThickness = 1;
                myPath.Data = myRectangleGeometry;
                CanvasSheet.Children.Add(myPath);
            }
        }
    }
}

如果我改myPath.Fill = myBlueBrush;使用原生刷myPath.Fill = Brushes.Red;速度会提高很多

如何在不牺牲速度的情况下使用自定义 SolidColorBrush

谢谢

使用前需要Freeze刷机以提高性能。添加

myBlueBrush.Freeze();

在 userControl 构造函数中 InitializeComponent(); 之后。

Brushes class 初始化后冻结其画笔。参见 source code of KnownColors.SolidColorBrushFromUint