5

我正在画一个矩形,睡了几毫秒——然后我想清除矩形,但我不知道怎么做。(矩形位于图形上方,因此我不能简单地用另一个矩形覆盖它)

                graphics.DrawRectangle(p, innerRectangle)
                System.Threading.Thread.Sleep(75)
                Next I want to clear the rectange...
4

4 回答 4

5

您需要重新绘制图形(或至少在矩形下方的部分)。如果这是一个图片框或类似的东西,请使用Invaldiate()强制重新绘制。

于 2009-06-11T19:30:30.100 回答
2

我想在绘制矩形之前将原始数据从表面复制到临时位图中,然后将位图绘制回原位应该可以。

更新

已经有一个公认的答案,但我想我还是可以分享一个代码示例。这个在给定控件上用红色绘制给定矩形,并在 500 毫秒后恢复该区域。

public void ShowRectangleBriefly(Control ctl, Rectangle rect)
{
    Image toRestore = DrawRectangle(ctl, rect);
    ThreadPool.QueueUserWorkItem((WaitCallback)delegate
    {
        Thread.Sleep(500);
        this.Invoke(new Action<Control, Rectangle, Image>(RestoreBackground), ctl, rect, toRestore);
    });
}

private void RestoreBackground(Control ctl, Rectangle rect, Image image)
{
    using (Graphics g = ctl.CreateGraphics())
    {
        g.DrawImage(image, rect.Top, rect.Left, image.Width, image.Height);
    }
    image.Dispose();
}

private Image DrawRectangle(Control ctl, Rectangle rect)
{
    Bitmap tempBmp = new Bitmap(rect.Width + 1, rect.Height + 1);
    using (Graphics g = Graphics.FromImage(tempBmp))
    {
        g.CopyFromScreen(ctl.PointToScreen(new Point(rect.Top, rect.Left)), new Point(0, 0), tempBmp.Size);
    }

    using (Graphics g = this.CreateGraphics())
    {
        g.DrawRectangle(Pens.Red, rect);
    }
    return tempBmp;
}
于 2009-06-11T19:30:46.870 回答
2

If the rectangle is sitting completely over the graphic you should be able to just redraw or refresh the underlying graphic. If it is not, you will need to redraw the rectangle using the background color, and then refresh the underlying graphic.

于 2009-06-11T19:31:12.690 回答
1

I had the same problem and resolved it with an extra panel drawn on the main form and shown/hidden, sized and positioned as necessary.

SelectionBox box = new SelectionBox();
box.Location = location;
box.Size = size;
box.Visible = true;

Then when rectangle is not necessary anymore, just hide it by calling:

box.Visible = false;

The panel class is made with transparency to ensure that overlay graphics does not hide other content of the window.

  [System.ComponentModel.DesignerCategory("Code")]
  public class SelectionBox : Panel
  {
    protected override void OnPaint(PaintEventArgs e)
    {
      const int penWidth = 2;
      int offset = penWidth - 1;
      using (Pen pen = new Pen(Color.Red, 2))
        e.Graphics.DrawRectangle(pen, offset, offset, 
          ClientSize.Width - offset - 1, ClientSize.Height - offset - 1);
    }

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
        return cp;
      }
    }
  }
于 2017-04-08T07:59:03.673 回答