I m trying to fill a Canvas
with some random shapes( Ellipse
and Rectangle
). I need to pick a random color to fill the shapes with it. The problem that I have always the same random color for all the shape.
When I debug my code I get random colors. Below is my Code :
public MainWindow()
{
InitializeComponent();
this.Loaded += delegate { InitializeSourceCanvas(); };
}
private void InitializeSourceCanvas()
{
var rnd = new Random();
const int height = 30, width = 30;
for (int i = 0; i < 25; i++)
{
var shape = rnd.Next(10) > 4 ? (Shape)new Ellipse() : (Shape)new Rectangle();
shape.Width = height;
shape.Height = width;
shape.Stroke = new SolidColorBrush(Colors.Black);
shape.StrokeThickness = 1;
shape.Fill = PickRandomBrush();
Canvas.SetLeft(shape, rnd.NextDouble() * (_source.ActualWidth - width));
Canvas.SetTop(shape, rnd.NextDouble() * (_source.ActualHeight - height));
_source.Children.Add(shape);
}
}
private Brush PickRandomBrush()
{
Brush result = Brushes.Transparent;
Random rnd = new Random();
Type brushesType = typeof(Brushes);
PropertyInfo[] properties = brushesType.GetProperties();
int random = rnd.Next(properties.Length);
result = (Brush)properties[random].GetValue(null, null);
return result;
}