How to draw a rectangle using WriteableBitmap?

1.3k Views Asked by At

I created a WPF project which just includes an Image control.

<Image 
  x:Name='img'
  Width='256'
  Height='256'
  MouseDown='img_MouseDown' />

My goal is to click the image and draw a 10 pixel side square, of white color, at the specific position where the click happened.

At the begining I tried to draw 1 pixel sized squares and worked as expected.

enter image description here

Here is that code:

 public partial class MainWindow : Window
    {
        WriteableBitmap wb;

        public MainWindow()
        {
            InitializeComponent();
            wb = new WriteableBitmap(256, 256, 96d, 96d, PixelFormats.Bgr24, null);
            img.Source = wb;
        }

        private void img_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(img);

            Int32Rect rect = new Int32Rect((int)p.X, (int)p.Y, 1, 1);
            int stride = wb.PixelWidth * wb.Format.BitsPerPixel / 8;
            byte[] buffer = { 255, 255, 255 };
            wb.WritePixels(rect, buffer, stride, 0);
        }
    }

Now that I want to draw a 10 pixel size square I am initializing the rect with 10 pixels width and height,

Int32Rect rect = new Int32Rect((int)p.X, (int)p.Y, 10, 10);

,but WritePixels() throws an Exception saying "Buffer size is not sufficient." Out of desperation I've changed the buffer to have 10 size but still getting the same error.

What is the problem here?

1

There are 1 best solutions below

2
Clemens On BEST ANSWER

The stride argument is meant to be that of the input buffer, i.e. 3 x 10 here:

var width = 10;
var height = 10;
var stride = (width * wb.Format.BitsPerPixel + 7) / 8;
var rect = new Int32Rect((int)p.X, (int)p.Y, width, height);
var buffer = Enumerable.Range(0, stride * height).Select(i => (byte)255).ToArray();
wb.WritePixels(rect, buffer, stride, 0);