我正在绘制一个矩形,休眠几毫秒 - 然后我想清除矩形,但我无法弄清楚如何。 (矩形坐在在图形上,所以我不能简单地用另一个矩形遮掩了)清除Windows窗体中的DrawRectangle
graphics.DrawRectangle(p, innerRectangle)
System.Threading.Thread.Sleep(75)
Next I want to clear the rectange...
我正在绘制一个矩形,休眠几毫秒 - 然后我想清除矩形,但我无法弄清楚如何。 (矩形坐在在图形上,所以我不能简单地用另一个矩形遮掩了)清除Windows窗体中的DrawRectangle
graphics.DrawRectangle(p, innerRectangle)
System.Threading.Thread.Sleep(75)
Next I want to clear the rectange...
您需要重新绘制图形(或它的矩形下至少部分)。如果这是一个图片框或类似的东西,请使用Invaldiate()强制重绘。
我想它应该能够在绘制矩形之前将原始数据从表面复制到临时位图,然后将位图绘制回原处。
更新
已经有一个公认的答案,但我想我可以分享反正一个代码示例。这个在给定的控件上绘制给定的红色矩形,并在500 ms后恢复该区域。
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;
}
如果矩形完全位于图形上,则应该只能重绘或刷新底层图形。如果不是,则需要使用背景颜色重新绘制矩形,然后刷新底层图形。
我有同样的问题,并解决它在主窗体上绘制一个额外的面板,并根据需要显示/隐藏,大小和位置。
SelectionBox box = new SelectionBox();
box.Location = location;
box.Size = size;
box.Visible = true;
然后,当矩形不再是必需的,只是通过调用隐藏:
box.Visible = false;
面板类与透明度,以确保该覆盖图形不隐藏窗口的其他内容。
[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-12 08:11:36