user1208402
user1208402

Reputation: 117

How to have a scrolling panel with a picturebox inside?

I have a panel that is anchored to the top, left, right, bottom of a Windows form. Inside that panel is a picturebox. That picturebox is resized up and down via a TrackBar control (which is on another panel on the same form with 'Dock' property set to Top), and re-centered every time it is resized. The picturebox occasionally grows either too wide or too tall for the panel to contain it. How can I add horizontal and vertical scrollbars to the panel to allow it to 'pan' the image within the picturebox? I've tried using the autoscroll property, but I can't seem to get it to do anything and the MSDN documentation is somewhat vague and lists some bugs. I've looked over the previous questions here on stack, but can't find anything that works for my situation. Any ideas?

I'm using Visual Studio 2010 and a VB.NET project, but VB.NET or C# recommendations would be great.

Thanks in advance!

Upvotes: 1

Views: 2883

Answers (1)

LarsTech
LarsTech

Reputation: 81675

There isn't a single setting for that type of action, because when a PictureBox dimension is smaller than the Panel's client space, you want the PictureBox to be centered, but when the PictureBox dimensions exceeds the size of the Panel's client space, you want the location to be at point zero and have the scrollbar handle the view.

Try handling the panel's resize event and also call the event when you resize the PictureBox:

Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
  PictureBox1.Size = New Size(64 * TrackBar1.Value, 64 * TrackBar1.Value)
  Panel1.AutoScrollMinSize = PictureBox1.Size
  Panel1_Resize(Panel1, EventArgs.Empty)
End Sub

Private Sub Panel1_Resize(sender As Object, e As EventArgs) Handles Panel1.Resize
  If PictureBox1.Width > Panel1.ClientSize.Width Then
    PictureBox1.Left = Panel1.AutoScrollPosition.X
  Else
    PictureBox1.Left = Panel1.ClientSize.Width / 2 - PictureBox1.Width / 2
  End If

  If PictureBox1.Height > Panel1.ClientSize.Height Then
    PictureBox1.Top = Panel1.AutoScrollPosition.Y
  Else
    PictureBox1.Top = Panel1.ClientSize.Height / 2 - PictureBox1.Height / 2
  End If
End Sub

Upvotes: 2

Related Questions