1

I create a WriteableBitmap object, draw a line and try to set it as the source to an Image control. For some reason, the program stops responding and then closes 5 seconds later when I try to set the Source. Anyone have any idea what's wrong? (I am also using WriteableBitmapEx)

WriteableBitmap bit = new WriteableBitmap(400, 400, 96, 96, PixelFormats.Bgr32, null);
WriteableBitmapExtensions.DrawLine(bit, 10, 10, 300, 300, Core.PrimaryColor.ColorValue);
ImageCanvas.Source = bit; // Sets the image to our bitmap, but program crashes for some reason!
Anders Gustafsson
  • 15,837
  • 8
  • 56
  • 114
Oztaco
  • 3,399
  • 11
  • 45
  • 84

1 Answers1

3

When I try your code, it throws an ArgumentException saying

The input WriteableBitmap needs to have the Pbgra32 pixel format. Use the BitmapFactory.ConvertToPbgra32Format method to automatically convert any input BitmapSource to the right format accepted by this class.\r\nParametername: writeableBitmap

Hence this works:

var bitmap = new WriteableBitmap(400, 400, 96, 96, PixelFormats.Pbgra32, null);
WriteableBitmapExtensions.DrawLine(bitmap, 10, 10, 300, 300, Colors.Black);
image.Source = bitmap;

UPDATE: As noted by Anders, you should perhaps use the portable bitmap factory method provided by WriteableBitmapEx to create your bitmap:

var bitmap = BitmapFactory.New(400, 400);
WriteableBitmapExtensions.DrawLine(bitmap, 10, 10, 300, 300, Colors.Black);
image.Source = bitmap;
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • 3
    +1 for spotting this. Just want to add that *WriteableBitmapEx* also provides a portable method for creating `WriteableBitmap`:s, `BitmapFactory.New(int pixelWidth, int pixelHeight)`. For WPF, this method uses exactly the above constructor arguments. Using the factory method instead of the explicit WPF based constructor makes it easier to port the code to other platforms, if so desired. – Anders Gustafsson Jun 20 '13 at 06:47
  • Excellent thanks, @AndersGustafsson +1 for `BitmapFactory.New` – Oztaco Jun 20 '13 at 21:58