簡體   English   中英

繪圖矩形覆蓋現有 bitmap c#

[英]Drawing rectangle is overwriting existing bitmap c#

我有一個已經繪制到圖片框的網格,我希望在單擊鼠標的單元格中繪制一個矩形。我試圖通過在單元格的左上角繪制一個矩形並讓它填充整個細胞。 然而,當我點擊網格消失。 我怎樣才能讓它保持網格?

有沒有明顯更好的方法來做到這一點?

重新繪制網格的唯一方法是再次按下按鈕,但我希望它留在那里。 謝謝。

在此處輸入圖像描述

您需要創建一個圖形

Image bm;// Or Bitmap
            
using (var graphics = Graphics.FromImage(bm))
{
    Draw(rects, graphics);              
}

private static void Draw(List<Rectangle> rectangles, Graphics graphics)
{
    Pen redPen = new Pen(Color.Red, 1);
    foreach (var rect in rectangles)
    {
        graphics.DrawRectangle(redPen, rect);
    }
}

在 mouse_click 事件中的每次鼠標單擊時,首先處理圖片框的圖像,然后再次將 bitmap 分配給圖片框圖像,否則如果單擊網格太多次,您可能會遇到 memory 異常

private void InitializePictureBoxImage(PictureBox pictureBox)
{
    if(pictureBox.Image != null)
    {
          var image = pictureBox.Image;  // cache it to dispose
          pictureBox.Image = null;  // don't dispose an used object
          image.Dispose();   // and dispose of it
    }

    Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
    pictureBox.Image = bitmap;  // assign bitmap to image
}
    

然后在單擊表單中的“生成網格”按鈕時調用用於繪制圖片框的 mouse_click 事件中的方法。 然后使用 mouse_click 事件中的圖形為您按下的網格着色,並從 MouseEventArgs 獲取 XY 坐標。

總而言之,我認為它會是這樣的

private void Mouse_ClickEvent(object sender, MouseEventArgs e)
{
    InitializePictureBoxImage(pictureBox);
    DrawThePictureBoxImage(pictureBox);

    using (Graphics graphics = Graphics.FromImage(pictureBox.Image))
    {
       Color color = Color.Blue;
       color = Color.FromArgb(150, color.R, color.G, color.B);  // lower the opacity so the writing in the grid is visible
       var brush = new SolidBrush(color);
       
       // Calculate the starting X-Y coordinate and Width,Height of the grid to color

       graphics.FillRectangle(brush, startX, startY,
                    width, height);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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