简体   繁体   English

自定义控件上的C#绘图

[英]C# drawing on custom controls

so I've created a custom control and I wanted to draw on that control now the problem is that I can't use OnPaint event because I want to draw at different times with different conditions. 因此,我创建了一个自定义控件,现在我想使用该控件,问题是我无法使用OnPaint事件,因为我想在不同时间,不同条件下绘制。

here is the custom control function to draw a rectangle 这是绘制矩形的自定义控件功能

 public void DrawARectangle(int x,int y,int height,int width) { Graphics g = this.CreateGraphics(); g.DrawRectangle(Pens.Black, x, y, height, width); g.FillRectangle(Brushes.Black, x, y, height, width); } 

and I basically call it from my form , but it doesn't draw anything even after using the update() method. 我基本上是从表单中调用它的,但是即使使用了update()方法,它也不会绘制任何内容。

You must use Control.OnPaint to do your custom drawing. 您必须使用Control.OnPaint进行自定义绘图。 Otherwise all of your drawings will be erased after the next repaint of your control. 否则,下一次重画控件后,所有图形都将被删除。 The idea is you may store your rectangles in a list. 想法是您可以将矩形存储在列表中。 Then in your Control.OnPaint , you do the drawing based on that list. 然后在Control.OnPaint ,基于该列表进行绘制。

Graphics g = this.CreateGraphics(); This is almost always wrong . 这几乎总是错误的

Use the Paint/OnPaint event and its e.Graphics parameter! 使用Paint/OnPaint事件及其e.Graphics参数! Store the coordinates somewhere and be prepared to always draw everthing.. 将坐标存储在某处,并准备随时绘制所有内容。

I can't use OnPaint event because I want to draw at different times with different conditions. 我无法使用OnPaint事件,因为我想在不同时间,不同条件下进行绘制。 Yes. 是。 But you must ! 但是你必须

This is how graphics work in winforms. 这就是Winforms中图形的工作方式。 This only sounds wasteful but..: The system also needs to call this event when the window must be restored, so there is no way around it if you want your drawing to persist .. 听起来浪费,但是..:当必须还原窗口时,系统还需要调用此事件,因此如果您希望图形继续存在 ,则无法解决此问题

Only non-persistent graphics operations like displaying a dynamic rubber-band rectangle or a line that follows the mouse, are ok with a Graphics object you get from control.CreateGraphics() . 对于从control.CreateGraphics()获得的Graphics对象,只有非持久的图形操作(例如显示动态橡皮筋矩形或跟随鼠标的线条control.CreateGraphics() And measurements without drawing... 无需测量即可测量...

Trigger re-drawing by calling Invalidate on your control whenever your data have changed. 每当数据更改时,通过在控件上调用Invalidate触发重新绘制。

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

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