TheMelon2012
TheMelon2012

Reputation: 1

Drawing a large grid of rectangles with WPF

Hi i'm in the process of trying to create a large 1000x1000 array of rectangles in WPF, where each point in the array i'm able to find the index position using cursor and click on the position to modify the colour of the rectangle.

I need the array to be generated quickly <0.1s

Currently i'm reading in my into and array and from this generating a bitmap image, which i scale and colour accordingly, but after many attempts the fastest i can generate the image is around 1s

Any suggestions on how this could be done faster? either generating the image faster or potentially a better method of generating the array

Thanks

Upvotes: 0

Views: 200

Answers (1)

JonasH
JonasH

Reputation: 36541

I do not think you will be able to draw 10^6 rectangles in 100ms. But that is a great deal of rectangle for a regular monitor. So you should probably consider what it is you are actually trying to do.

If you want a grid, just draw lines, that should reduce the number of draw calls to 1000+1000, much more manageable.

If you want a pixel aligned grid you could consider just iterating over every other row/pixel column in a bitmap and set the color. Typically using a writeablebitmap for fast access to the pixel-buffer. That should probably not take more than single digit ms. Manipulating pixels on this level will require some familiarity with how images are represented and how to convert x/y coordinates, i.e. var startOfPixelIndex = y * stride + x * bytesPerPixel if using a byte pointer.

If you want to color rectangles you probably want to work with a writeableBitmap and set individual, or small rectangles of pixels to your desired color. Ideally you should avoid recreating or clearing the entire bitmap, and instead just update the same bitmap over and over.

As far as I know there is no convenient way to draw to a WriteableBitmap, so in some cases it might make sense to use a GDI graphics object to draw to a regular bitmap, and copy the pixels over to a WriteableBitmap.

Upvotes: 1

Related Questions