[英]How to draw a rectangle using WriteableBitmap?
我创建了一个 WPF 项目,其中仅包含一个Image
控件。
<Image
x:Name='img'
Width='256'
Height='256'
MouseDown='img_MouseDown' />
我的目标是单击图像并在单击发生的特定 position 处绘制一个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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.