Victor Zakharov
Victor Zakharov

Reputation: 26414

Draw graphics on a form without lags?

Problem with my approach is that image, text or line drawn, lags by maybe 0.2 seconds, when resizing the form. So if you need an image in bottom right corner, it takes that 0.2 seconds to come in place after resize. Also, if you do heavy resizing, it starts lagging down to 1-2FPS, while the form expands on a big screen. Sample code looks like this (VB.NET):

Public Class Form1
  Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
    MyBase.OnPaint(e)
    Dim icon As Icon = SystemIcons.Exclamation
    Dim imageWidth As Integer = icon.Width
    Dim imageHeight As Integer = icon.Height
    e.Graphics.DrawIcon(icon, Me.ClientRectangle.Right - imageWidth,
                              Me.ClientRectangle.Bottom - imageHeight)
  End Sub
  Private Sub Form1_Resize(sender As Object, e As System.EventArgs) Handles Me.Resize
    Me.Invalidate()
  End Sub
End Class

Is there anything that can be done to make it smoother?

Upvotes: 0

Views: 3743

Answers (2)

Bob Powell
Bob Powell

Reputation: 146

Windows Forms provides a style setting to double buffer the screen. This does a lot of setup for you.

Also, double buffering gets rid of the need to clear the screen so overriding OnPaintBackground and returning without calling the base class will prevent a lot of work that will not be seen anyway.

For some of the best examples of GDI+ / winforms double buffering check out my animation examples.

Upvotes: 2

Neil
Neil

Reputation: 55382

Resizing your window is always going to involve redrawing the image in the new location. However, there are some things you can try that may or may not make the redrawing more efficient.

  1. Only invalidate the old and new position of the image, not the whole form. This means that you don't have to paint parts of the window that don't change.
  2. Copy the image from the old location to the new location. You have to be careful here to invalidate the right parts of the window, particularly when the window is getting smaller and the old and new image areas overlap.
  3. Create a separate control for the image, and move the control to the correct location. The form and the control will then automatically invalidate the correct regions.

Upvotes: 1

Related Questions