我正在使用Windows窗体应用程序,当我在图片框顶部使用System.Drawing.Graphics
时,图形要么在消失之前不会出现或暂时出现。< / p>
这是我用来设置图片框的代码(它是一个简化版本并且仍然展示了行为)
private void showGraphic()
{
pictureBox1.Invalidate();
System.Drawing.Graphics graphics = this.pictureBox1.CreateGraphics();
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);
graphics.FillEllipse(semiTransBrush, rect);
}
private void button1_Click(object sender, EventArgs e)
{
showGraphic();
}
图片框的设置只是默认设置,其中包含属性窗格中声明的文件中的图片。
我能够通过使用由按钮启动的计时器来解决这个问题,然后在停止之前执行图形绘制,但这似乎是一个非常糟糕的解决方案,我希望这样做更好,如果存在的话这可能导致旧计算机缺乏可移植性。
提前致谢
答案 0 :(得分:2)
您需要为PictureBox的Paint方法注册一个处理程序,并在该方法中进行绘制。 (注意:使用通过PaintEventArgs参数传入的Graphics对象。)这将保证在重新绘制PictureBox的任何时候,您的绘图代码也将运行。否则,您只是因为多种原因而掠过可以刷新的内容。
一旦您注册了Paint事件,只要您想重新绘制,请在PictureBox上调用Invalidate(),您的绘画代码将会运行。您可以跟踪是否应通过私有布尔成员变量绘制叠加图形。
答案 1 :(得分:0)
当您致电pictureBox1.Invalidate()
时,它会排队显示需要绘制图片框的消息。在处理该消息之前,您将在当前图片的顶部绘制一个椭圆。然后消息循环处理来自invalidate的paint消息,然后重新绘制自己(删除你的图像)
答案 2 :(得分:0)
To make this (old and answered) question more complete I'm adding an alternative solution: sometimes you don't want to redraw your picture every refresh, for example if drawing is complicated and takes time. For these cases, you can try the following approach:
For example:
// create a new bitmap and create graphics from it
var bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
var graphics = System.Drawing.Graphics.FromImage(bitmap);
// draw on bitmap
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);
graphics.FillEllipse(semiTransBrush, rect);
// set bitmap as the picturebox's image
pictureBox1.Image = bitmap;
With the code above you can draw everything once and it will survive redraw events.