简体   繁体   中英

How to draw a rectangle using WriteableBitmap?

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?

The stride argument is meant to be that of the input buffer, ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM