开发者

To avoid flickering in my code

开发者 https://www.devze.com 2022-12-22 00:12 出处:网络
I m drawing rectangle on mouse move in c#, i wrote the code like this, onmousemove: Rectangle rect = new Rectangle(

I m drawing rectangle on mouse move in c#,

i wrote the code like this,

onmousemove:

Rectangle rect = new Rectangle(
    Math.Min(mouseMovePoint.X, mouseDownPoint.X), 
   开发者_开发技巧 Math.Min(mouseMovePoint.Y, mouseDownPoint.Y),
    Math.Abs(mouseMovePoint.X - mouseDownPoint.X), 
    Math.Abs(mouseMovePoint.Y - mouseDownPoint.Y)
);

    graphics.DrawRectangle(myPen, rect);

onmouseup:

this.Refresh();

Rectangle rect = new Rectangle(
    Math.Min(mouseMovePoint.X, mouseDownPoint.X), 
    Math.Min(mouseMovePoint.Y, mouseDownPoint.Y),
    Math.Abs(mouseMovePoint.X - mouseDownPoint.X), 
    Math.Abs(mouseMovePoint.Y - mouseDownPoint.Y)
);

graphics.DrawRectangle(myPen, rect);

But due to this refresh method when i draw the rectangle it appears like as if it s flickering how to avoid that?


It appears that you aren't calling this code an override of the OnPaint method of your Control or the Paint event.

If that is the case, you should be overriding the OnPaint method or setting a handler for the Paint event.

Then, in your mouse events, you store the location of the mouse coordinates and call the Invalidate method on your Control to force a repaint of the control.

Finally, in the override of OnPaint or your Paint event handler, you would access the coordinates/rectangle data that you set in the mouse events, and paint the rectangles there, using the Graphics instance passed to the OnPaint method/Paint event through the Graphics property on the PaintEventArgs class.


Use ControlPaint.DrawReversibleFrame for drawing selection boxes, in conjunction with MouseDown, MouseMove and MouseUp events. Check this on MSDN.


Enable DoubleBuffering should fix this.


Enable double buffering like suggested above, also use Invalidate instead of Refresh. You should get far better performance out of it.


The traditional way to avoid flickering, in any circumstances is by drawing all the staff (very time consuming in certain cases) on a bitmap and then sending the bitmap once in the drawing canvas (in a snapshot). Although GDI or GDI+ is not OpenGL, in terms of performance, however this approach, really boosts performance (I've used it in real applications drawing 1-10 million objects).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号