如何使用 WriteableBitmap 绘制矩形?

How to draw a rectangle using WriteableBitmap?

我创建了一个只包含 Image 控件的 WPF 项目。

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

我的目标是单击图像并在发生单击的特定位置绘制一个 10 像素的白色正方形

一开始我尝试绘制 1 个像素大小的正方形并按预期工作。

代码如下:

 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);
        }
    }

现在我想绘制一个 10 像素大小的正方形,我正在用 10 像素的宽度和高度初始化 rect

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

,但 WritePixels() 抛出异常,提示“缓冲区大小不足。”出于绝望,我已将缓冲区大小更改为 10,但仍然得到同样的错误。

这里有什么问题?

stride 参数是输入缓冲区的参数,即这里的 3 x 10:

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);