I create a game in WPF.
My goal is to create ellipses at random free positions of a canvas.
I need to exclude positions overlaid by created ellipses and create new ellipses on free random positions.
I tried VisualTreeHelper.HitTest and Geometry FillContains, but they are slow.
How can i do it in WPF?
Code (fixed timer):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
public Canvas canvas;
Random random = new Random();
int add = 5;
Timer timerEllipses;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
canvas = new Canvas();
canvas.Background = Brushes.Black;
this.Content = canvas;
timerEllipses = new Timer();
timerEllipses.Interval = 1;
timerEllipses.Start();
Timer timer = new Timer();
timer.Interval = 2000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
int add = this.add;
int x = random.Next((int)canvas.ActualWidth);
int y = random.Next((int)canvas.ActualHeight);
for (int i1 = 0; i1 < canvas.ActualWidth; i1++)
for (int i2 = 0; i2 < canvas.ActualHeight; i2++)
VisualTreeHelper.HitTest(canvas, new Point(i1, i2));
Ellipse ellipse = new Ellipse();
ellipse.Width = 1;
ellipse.Height = 1;
ellipse.Stroke = Brushes.White;
canvas.Children.Add(ellipse);
timerEllipses.Elapsed += delegate
{
this.Dispatcher.Invoke((Action)(() =>
{
ellipse.Width += add;
ellipse.Height += add;
ellipse.Margin = new Thickness(x - (ellipse.Width / 2), y - (ellipse.Height / 2), 0, 0);
}));
};
}));
}
}
You can see how a separate thread doesn't help in my code when i hit test the canvas to get free points.
Code (separate thread):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
public Canvas canvas;
Random random = new Random();
Ellipse ellipse;
int add = 5;
double x = 0;
double y = 0;
Stopwatch stopwatch = new Stopwatch();
public double elapsed = 10;
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
canvas = new Canvas();
canvas.Background = Brushes.Black;
this.Content = canvas;
ellipse = new Ellipse();
ellipse.Width = 1;
ellipse.Height = 1;
ellipse.Stroke = Brushes.White;
canvas.Children.Add(ellipse);
new System.Threading.Thread(Thread1).Start();
}
void Thread1()
{
stopwatch.Start();
while (true)
{
if (stopwatch.Elapsed.TotalMilliseconds >= elapsed)
{
stopwatch.Stop();
this.Dispatcher.Invoke((Action)(() =>
{
for (int i1 = 0; i1 < canvas.ActualWidth; i1++)
for (int i2 = 0; i2 < canvas.ActualHeight; i2++)
VisualTreeHelper.HitTest(canvas, new Point(i1, i2));
ellipse.Width += add;
ellipse.Height += add;
ellipse.Margin = new Thickness(x - (ellipse.Width / 2), y - (ellipse.Height / 2), 0, 0);
}));
stopwatch.Restart();
}
}
}
}