I
I
Ifry2015-08-25 11:59:56
Microcontrollers
Ifry, 2015-08-25 11:59:56

How to correctly display a large number of Ellipse on Canvas (WPF)?

On a form (WPF) there is a canvas and a button. When the button is pressed, a timer is started, which every 100ms draws a large number of ellipses (about 5 thousand). Here is an example of how I draw them:

public partial class MainWindow : Window
    {
        DispatcherTimer Timer;
        public MainWindow()
        {
            InitializeComponent();
            Timer = new DispatcherTimer();
            Timer.Tick += new EventHandler(Timer_Tick);
            Timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            canvas.Children.Clear();
            Random rnd = new Random(DateTime.Now.Millisecond);
            for (int j = 0; j < 5000; j++)
            {
                Ellipse ell = new Ellipse();
                ell.Height = 6;
                ell.Width = 6;
                ell.Fill = Brushes.Black;
                ell.Margin = new Thickness(
                    rnd.Next(0, 300),
                    rnd.Next(0, 300),
                    0,
                    0);
                canvas.Children.Add(ell);
            }
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            Timer.Start();
        }
    }

The problem is that with such a large number of ellipses, there is a heavy load on the CPU. How can I do it right and reduce the load on the CPU?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2015-08-25
@Ifry

To begin with, it is worth considering how you can create ellipses once, and not every 100 milliseconds. Graphics objects in WPF are quite heavy, and it is better to create them once and then reuse them.

A
AxisPod, 2015-08-25
@AxisPod

Naturally, what else to expect. The simplest thing is to draw them into a buffer of some kind, which you then output to the canvas. And the second is to dig towards Direct2D (primitives out of the box), if there is enough support from 8ki and above, if not, then towards other graphic APIs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question