C# 使图形无效
我有一个矩形的图形对象,这是在点击picturebox上的按钮时创建的,但是如果窗体从屏幕上移开,图形会消失,整个窗体也会变白。我尝试过使picturebox无效,但这会停止按钮的工作。有人能帮我将对象保留在窗体上吗使用无效方法我知道有一种方法,但我似乎无法掌握它C# 使图形无效,c#,gdi+,C#,Gdi+,我有一个矩形的图形对象,这是在点击picturebox上的按钮时创建的,但是如果窗体从屏幕上移开,图形会消失,整个窗体也会变白。我尝试过使picturebox无效,但这会停止按钮的工作。有人能帮我将对象保留在窗体上吗使用无效方法我知道有一种方法,但我似乎无法掌握它 private void squareButton_Click(object sender, EventArgs e) { // Declaring a new graphics obje
private void squareButton_Click(object sender, EventArgs e)
{
// Declaring a new graphics object has been assigned null
Graphics objGraphics = null;
// This will create the picture graphics to be drawn in the picturebox
objGraphics = PictureBox1.CreateGraphics();
// This will redraw the picture box with a fill chosen after the systemcolors
objGraphics.Clear(SystemColors.ControlDark);
// This will draw the rectangle with a red pen 10,10 represent position and 50,50 reprsent the width and height
objGraphics.DrawRectangle(Pens.Red, 10, 10, 50, 50);
// This will draw the rectangle
objGraphics.Dispose();
invalidate(PictureBox1);
// This is not redrawing the graphic it just shows a blank form
}
试试这个:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics objGraphics = null;
// This will create the picture graphics to be drawn in the picturebox
objGraphics = e.Graphics;
// This will redraw the picture box with a fill chosen after the systemcolors
objGraphics.Clear(SystemColors.ControlDark);
// This will draw the rectangle with a red pen 10,10 represent position and 50,50 reprsent the width and height
objGraphics.DrawRectangle(Pens.Red, 10, 10, 50, 50);
// This will draw the rectangle
//objGrphics.Dispose();
}
不要使用CreateGraphics。使用PictureBox的Paint事件,然后只需调用
PictureBox1.Invalidate()告诉windows调用该控件的paint方法。但是为我们绘制一个事件处理程序我如何像使用方法一样使用它呢使用paint事件处理程序对新程序员来说可能有点生疏。你不必,你可以创建一个简单的画布。将新位图指定给构造函数中的PictureBox.Image属性,并使用Graphics.FromImage()绘制到该位图。调用Invalidate()为了把它画到屏幕上。谢谢,我现在正试着按照你说的做这件事,看起来完全一样,我是一个初学者。你能帮我把代码放在这里吗?我能不能在点击按钮时不使用invalidate,或者我必须在画图中使用它,即使在PictureBox上也可以只放pictureBox1.invalidate();在按钮单击事件中。