We are building a graphical application, we need to draw dots on the canvas background, as we have a feature like Snap To Grid
Of course, user can set the distance between snapping dots, so, if we have a canvas of size 1024 x 1024, with 5 pixels between each dot, we will have around 41775 dot!
What’s the recommended way to render this high number of dots on the canvas ? we need it to be as fast as possible.
WPF doesn’t have a direct method to draw pixels on a Canvas. The optimal way to implement it would be with Image and a WriteableBitmap source. Take a look at the code below. It has two functions: drawGrid1 and drawGrid2. On my machine, the first function (draws Ellipse element) takes 6 seconds. The latter function takes 50 milliseconds.
The code below is just for illustration. You could cache the WritebaleBitmap, and you should be sensitive (if your scenario requires) changes in the width or height (or, just create a very big bitmap). If you need even more performance, and you are OK with unsafe code, you can call WritebaleBitmap.Lock, then get WriteableBitmap.BackBuffer, and modify the back buffer manually. At the end, call WriteableBitmap.AddDirtyBuffer to invalidate the entire rectangle. It is also possible that if your Grid has only two colors, you can achieve even more performance, by using a palette.
More about WriteableBitmap: http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap(VS.85).aspx
XAML:
Code Behind: