簡體   English   中英

如何使用 WriteableBitmap 繪制一個矩形?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM