Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf 2d high performance graphics

Basically, I want GDI-type functionality in WPF, where I can write pixels to a bitmap and update and display that bitmap through WPF. Note, I need to be able to animate the bitmap on the fly by updating pixels in response to mouse movements. I've read that InteropBitmap is perfect for this, as you can write to pixels in memory and copy the memory location to the bitmap--but I don't have any good examples to go by.

Does anyone know of any good resources, tutorials, or blogs for using the InteropBitmap or some other classes for doing high-performance 2D graphics in WPF?

like image 294
Klay Avatar asked Sep 28 '09 15:09

Klay


2 Answers

Here's what I found:

I created a class that subclasses Image.

public class MyImage : Image {
    // the pixel format for the image.  This one is blue-green-red-alpha 32bit format
    private static PixelFormat PIXEL_FORMAT = PixelFormats.Bgra32;
    // the bitmap used as a pixel source for the image
    WriteableBitmap bitmap;
    // the clipping bounds of the bitmap
    Int32Rect bitmapRect;
    // the pixel array.  unsigned ints are 32 bits
    uint[] pixels;
    // the width of the bitmap.  sort of.
    int stride;

public MyImage(int width, int height) {
    // set the image width
    this.Width = width;
    // set the image height
    this.Height = height;
    // define the clipping bounds
    bitmapRect = new Int32Rect(0, 0, width, height);
    // define the WriteableBitmap
    bitmap = new WriteableBitmap(width, height, 96, 96, PIXEL_FORMAT, null);
    // define the stride
    stride = (width * PIXEL_FORMAT.BitsPerPixel + 7) / 8;
    // allocate our pixel array
    pixels = new uint[width * height];
    // set the image source to be the bitmap
    this.Source = bitmap;
}

WriteableBitmap has a method called WritePixels, which takes an array of unsigned ints as pixel data. I set the source of the image to be the WriteableBitmap. Now, when I update the pixel data and call WritePixels, it updates the image.

I store the business point data in a separate object as a List of Points. I perform transformations on the list, and update the pixel data with the transformed points. This way there's no overhead from Geometry objects.

Just FYI, I connect my points with lines drawn using something called Bresenham's algorithm.

This method is extremely fast. I'm updating about 50,000 points (and connecting lines) in response to mouse movements, with no noticeable lag.

like image 192
Klay Avatar answered Oct 17 '22 10:10

Klay


Here's a blog post on using Web cameras with InteropBitmap. It includes a full source code project demonstrating the InteropBitmap's usage.

like image 24
Reed Copsey Avatar answered Oct 17 '22 10:10

Reed Copsey