简体   繁体   English

如何使用 WriteableBitmap 绘制一个矩形?

[英]How to draw a rectangle using WriteableBitmap?

I created a WPF project which just includes an Image control.我创建了一个 WPF 项目,其中仅包含一个Image控件。

<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.我的目标是单击图像并在单击发生的特定 position 处绘制一个10 像素的白色边正方形

At the begining I tried to draw 1 pixel sized squares and worked as expected.一开始我尝试绘制 1 像素大小的正方形并按预期工作。

在此处输入图像描述

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,现在我想绘制一个 10 像素大小的正方形,我正在用 10 像素的宽度和高度初始化rect

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. ,但是WritePixels()抛出一个异常,说“缓冲区大小不够。 ”出于绝望,我将缓冲区更改为 10 大小,但仍然出现相同的错误。

What is the problem here?这里有什么问题?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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