The following code effectively creates a 2D grid of rectangles, my issue is that when I use a custom SolidColorBrush
the rendering becomes really slow.
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);
}
}
}
}
If I change myPath.Fill = myBlueBrush;
to use a native brush myPath.Fill = Brushes.Red;
the speed improves a lot.
How can I use a custom SolidColorBrush
without sacrificing speed?
Thanks
you need to Freeze
brush before using it to improve performance. add
myBlueBrush.Freeze();
after InitializeComponent();
in userControl constructor.
Brushes
class freezes its brushes after initializing them. see source code of KnownColors.SolidColorBrushFromUint