How to write 10 pixels at once to an Image using WriteableBitmap?

T

Themelis

Guest
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.

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?

Continue reading...
 
Top