Tag Archives: wrong offset

Scrollable panels and the Paint event.

When a panel has scrollbars ‘default’ drawing on the DC does not  work correctly when the upper-left is not at 0,0.  Graphics functions draw on the current client area, even when scrolled the upper-left posotion of the client area is still at 0,0.

Use the function TranslateTransform to offset the coordinates.

Example

private void dc_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.TranslateTransform(dc.AutoScrollPosition.X, dc.AutoScrollPosition.Y);
   //0,0 is now relative to the total scrollable area, not the visible part (client area).
}

Notes:

Although this will work great for simple drawing and unnecessary drawing is limited (being clipped ), some form of optimization would speed things up considerably.

To setup a larger DC size as visible set the properties AutoScroll to  true and the property AutoScrollMinSize to a size larger then the visible area.

Lastest update in May 2011, inital post in May 2011