简体   繁体   中英

GDI drawing application with high CPU usage

I have an application where the user draws some shapes. When I click over a shape and I drag it, the CPU goes 100% because of Invalidate() inside MouseMove. If I a use a timer and call Invalidate() from tick event the moving is not so smooth. Is there any other approach to minimize CPU and have smooth moving?

  ` Point startDragMousePoint;
    Point startShapeLocation;
    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if(isMouseDown)
        {
            Point deltaPoint = Point.Subtract(e.Location, new Size(startDragMousePoint));
            shape.Location = Point.Add(startShapeLocation, new Size(deltaPoint));
            Invalidate();
        }
    }

    private void Canvas_Paint(object sender, PaintEventArgs e)
    {
       shape.Render(e.Graphics);
    }`

There are three general solutions.

1) Don't draw while your moving, this was the solution in windows for a long time, when you dragged a window, it just disapeard and you saw the outline of a window.

2) Create a bitmap object and only move that. Note you will have to redraw the area under it.

3) Don't invalidate the hole window, just the area you are changing. Drawing to a buffer (a bitmap) can help you reuse areas.

Also, if GDI isn't the fastest drawing functions in the world. If your shape is very complex, you might want to consider using OpenGL, DirectX or SDL.

Instead of invalidating the entire area you could invalidate the portion of the control that has changed by using:

Rectangle changedArea = new Rectangle(cX, cY, cW, cH);
this.Invalidate(changedArea);

Also make sure your control is set to use DoubleBuffering

 this.DoubleBuffered = true;

From the limited code that you have put up, I think the invalidate will not cause any problem. Most probably the problem may be inside the real rendering code of yours shape.Render(). In the past I have written similar application where I have called Invalidate in the mouse move and the applications has worked fine. Only there were some flickering which is gone on enabling double buffering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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