简体   繁体   English

如何在C#中清除面板的图形?

[英]How to clear panel's graphics in c#?

I have used grahics in a panel. 我在面板中使用了grahics。 At start of the program I draw some points in the panel and after that I want to draw lines connecting those points. 在程序开始时,我在面板上绘制了一些点,然后我想绘制连接这些点的线。 Problem is when I press tab button the graphics created disappear (but this happens once in the program). 问题是,当我按下Tab键时,创建的图形消失了(但是在程序中一次发生)。 Next problem is I want to clear the panel I used following code to clear panel: 下一个问题是我想清除面板,我使用以下代码清除面板:

Panel1.Invalidate();

But this only clears the lines but not those points that were initially created. 但这只会清除线,而不会清除最初创建的点。 Does anyone has a simple solution because I don't want to recreate the panel. 没有人有一个简单的解决方案,因为我不想重新创建面板。

Technical Detail: to draw initial points in panel, paint event of panel1 is used: 技术细节:要在面板中绘制初始点,将使用panel1绘画事件:

Graphics gfx = e.CreateGraphics()

For lines, there is a seprate function that is called on button click and in that I used: 对于行,有一个单独的函数,它在单击按钮时被调用,而我使用的是:

Graphics gfx = Panel1.CreateGraphics();

Another button that is used to clear panel has following code: 用于清除面板的另一个按钮具有以下代码:

Panel1.invalidate();

but it only clears the line graphics, not those initial points. 但它只会清除线条图形,而不会清除那些初始点。

I was making a mistake by creating initial points in the paint event of panel1. 我通过在panel1的绘画事件中创建初始点来犯错。 So everytime i call 所以每次我打电话

Panel1.Invalidate();

it recalls that paint event and those points are redrawn and not cleared. 它回想起绘画事件和那些点是重画的并且没有清除。

Do you save the points in some sort of collection and draw them in the Paint event? 您是否将点保存在某种集合中并在Paint事件中绘制它们?

Then you should empty the collection and then call the Invalidate 然后,您应该清空集合,然后调用Invalidate

The panel is redrawn inside the paint event. 该面板将在Paint事件中重新绘制。 It means that you have to draw everything inside this method, instead of accessing the graphics context directly. 这意味着您必须在此方法中绘制所有内容,而不是直接访问图形上下文。

This explains why everything you draw when you use Graphics gfx = Panel1.CreateGraphics(); 这解释了为什么在使用Graphics gfx = Panel1.CreateGraphics();时绘制所有内容的原因Graphics gfx = Panel1.CreateGraphics(); is lost every time the control is redrawn, since during the paint event, you are only drawing the initial points, nothing more. 每次重新绘制控件时都会丢失,因为在绘制事件期间,您仅绘制初始点,仅此而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM