Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / Visual Basic

Pan/scroll an image in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.64/5 (73 votes)
8 Sep 2006CPOL4 min read 288.2K   6.7K   57   73
Ever wanted to allow the user to move an image with the mouse? This is one way to do it.

Sample Image - PanExample.jpg

Introduction

This is a simple and concise example of how to truly pan an image. This isn't your typical "move the picturebox control around" panning and scrolling... check it out!

Background

"Pan" an image is a term often used by people familiar with graphics design. Basically, it means to move an image one direction or another. This can be accomplished in a number of ways, but two of the most popular ones are:

  1. Using scrollbars
  2. Left-clicking the image and dragging the image with the mouse

This example does both.

Using the code

Here are the steps involved:

  1. First, you need a form.
  2. Drop a Panel control onto the form, and set the Dock property to Fill.
  3. Drop a PictureBox into the Panel and set its location to 0, 0 (named pb1).
  4. Set the Image property to an image.
  5. Use the following code. Be sure your events are wired up.

How it works

The scrollbars are easy. They are automatically put in by using a Panel control to contain the PictureBox control and by setting the AutoScroll property to true. Actually, panning the image by dragging the image with the mouse is pretty easy too, but does requires a little coding.

First, we need a member variable to hold our starting point. This is the point we will capture when the user first clicks the left mouse button over the picture. We need to hold this value for use in other methods:

VB
Private m_PanStartPoint As New Point

We also need to set up the default properties of the Panel and the PictureBox (named pb1). We'll do this when the form loads:

VB
Private Sub Form1_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) _
            Handles MyBase.Load
    'Panel Settings
    Panel1.AutoScroll = True
    'Picture Box Settings
    pb1.SizeMode = PictureBoxSizeMode.AutoSize
End Sub

Next, we need to hook into the MouseDown event of the PictureBox. We will first test to see if the left mouse button is down. If it is, then we can set the starting point member variable we declared above:

VB
Private Sub pb1_MouseDown(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles pb1.MouseDown
    'Capture the initial point 
    m_PanStartPoint = New Point(e.X, e.Y)
End Sub

Finally, we will need to listen for the MouseMove event. Here, we will first test to see if the left mouse button is down. If so, we can start panning. The first thing we need to do is calculate what direction they are going. We do this by capturing the change in position and saving them to variables named DeltaX and DeltaY. We can then use this information to set the new auto-scroll position of the panel:

VB
Private Sub pb1_MouseMove(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles pb1.MouseMove
    'Verify Left Button is pressed while the mouse is moving
    If e.Button = Windows.Forms.MouseButtons.Left Then

        'Here we get the change in coordinates.
        Dim DeltaX As Integer = (m_PanStartPoint.X - e.x) 
        Dim DeltaY As Integer = (m_PanStartPoint.Y - e.y) 

        'Then we set the new autoscroll position.
        'ALWAYS pass positive integers to the panels autoScrollPosition method
        Panel1.AutoScrollPosition = _
        New Drawing.Point((DeltaX - Panel1.AutoScrollPosition.X) , _
                        (DeltaY - Panel1.AutoScrollPosition.Y) )
    End If
End Sub

One thing to keep in mind is that the coordinates the AutoScrollPosition property returns are always going to be negative. The coordinates you pass back though are going to be positive. I know this sounds counter-intuitive, but that is how it works. The formulas above will produce positive numbers to pass to the AutoScrollPosition property.

So, to review, we are capturing the initial left click position. Then, when the user begins to "drag" the image, we calculate the change in coordinates. Once we have the new change in coordinates, we can calculate the new scroll position and pass that information back to the "autoScroll" method of the Panel control.

Pretty easy, huh?

Alternatively...

You could put the code to move the image in the MouseUp event instead of the MouseMove event. The main reason to do it this way is for efficiency. In the MouseUp event, you would only redraw the image once after the user has finished dragging the image, instead of each time the MouseMove event fires. The downside is that the user would lose the graphical feedback of actually seeing the image move as they drag the mouse.

Hiding the scrollbars

If you would like to use the above code, but do not wish to see the scrollbars for the Panel, here is an idea. First, create a new control that inherits from Panel. Second, add the following snippet of code:

VB
Protected Overrides Sub DefWndProc(ByRef m As Message)
    If m.Msg <> 131 Then
        MyBase.DefWndProc(m)
    End If
End Sub

Use this new control instead of the native panel control. This will give you a control without visible scrollbars. They are still there as far as the control is concerned; they just weren't painted to the screen. Therefore, you will still be able to use the panel's AutoScroll property and AutoScrollPosition method.

By hiding the panel's scrollbars, you could easily implement your own cool scrollbars.

Please note...

This is by no means meant to be a complete solution. Many times, there is more than one way to solve a problem. Hopefully though, this sample has proven beneficial in some way. Perhaps you have learned something about the AutoScrollPosition method? Perhaps this article has given you some great ideas about a better way to do this. Great! That's why I wrote it. Please feel free to leave some feedback. Let me know how it went for you. If you have some ideas on how to do this another way, or how to improve this example, please let me know that too.

Don't forget to vote! If you don't have an account, make one!

History

  • 05/22/2006, Version 1.0.0: Initial post.
  • 06/09/2006, Version 1.0.1: Revisited the formulas for readability.
  • 07/24/2006, Version 1.0.2: Added the "Alternatively" section.
  • 09/08/2006, Version 1.0.3: Added a section on hiding the scrollbars.

Special thanks to...

  • ITinka for his comments on larger images.
  • spammeagainagain for his suggestion to use the MouseUp event.
  • PolyMorpher for his question/suggestion on hiding the panel scrollbars.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I started my career in software development back in 2000. Prior to that, I made my living as a detail drafter. My true start in programming, though, goes back much further. I first started learning to program when I was about 10 years old. It was back in ‘82 that I wrote my first application. It was a simple calculator program written on a TRS-80 that my uncle had. Since then, I’ve programmed in Basic, QuickBasic, Pascal, C++, VB 6, VB.NET, Java, HTML, and C #. I have a very diverse background. I’ve worked and written software for several types of companies, including manufacturing, engineering, and finance. I’ve had the opportunity to design and maintain a few enterprise level databases, I’ve written applications to run on windows CE, in a wireless manufacturing environment. I’ve also had opportunities to teach OOP methodologies, and design patterns. I thoroughly enjoy what I do, and my only regret is that I didn’t start sooner.

Comments and Discussions

 
QuestionThank You Pin
Member 106445846-Jul-18 6:11
Member 106445846-Jul-18 6:11 
QuestionMuy buen trabajo Pin
Adndigital8-Jul-17 5:10
Adndigital8-Jul-17 5:10 
GeneralThank you, this works great. Pin
Greg Moller15-May-16 7:43
Greg Moller15-May-16 7:43 
Questionhow to scroll image in a picture box using keypress Pin
saravanahara2-Oct-15 21:31
saravanahara2-Oct-15 21:31 
QuestionCurious Question Pin
newellr6-Mar-13 22:40
newellr6-Mar-13 22:40 
Questionlinking two Anthony Queen's image control Pin
Member 859559625-Jan-12 1:05
Member 859559625-Jan-12 1:05 
AnswerRe: linking two Anthony Queen's image control Pin
Anthony Queen25-Jan-12 4:40
Anthony Queen25-Jan-12 4:40 
QuestionGood Pin
carliecode11-Nov-11 20:46
carliecode11-Nov-11 20:46 
GeneralVery good Pin
Anthony Daly17-Oct-10 1:47
Anthony Daly17-Oct-10 1:47 
Questioni need to implement feature called cropImage in your control in order to crop the image please help me. Pin
aasif aslam29-Jun-10 23:17
aasif aslam29-Jun-10 23:17 
GeneralMy vote of 5 Pin
JC Velasquez29-Jun-10 21:40
JC Velasquez29-Jun-10 21:40 
GeneralGracias, me has ayudado Pin
flealg1-Jun-10 15:43
flealg1-Jun-10 15:43 
QuestionLooks Great [modified] Pin
cds toecutter7-Jan-10 13:56
cds toecutter7-Jan-10 13:56 
GeneralVery Nice Pin
Member 291030324-Oct-09 20:38
Member 291030324-Oct-09 20:38 
Questioncode Pin
loguchandru19-Nov-08 17:53
loguchandru19-Nov-08 17:53 
Generalcredit Pin
ehabhassan27-May-08 6:39
ehabhassan27-May-08 6:39 
Generalthank! Pin
zhmvb@tom.com20-May-08 23:58
zhmvb@tom.com20-May-08 23:58 
GeneralUpdate Pin
Anthony Queen26-Oct-06 4:29
Anthony Queen26-Oct-06 4:29 
GeneralScrolled Image size Pin
Rob Brookes12-Sep-06 5:57
Rob Brookes12-Sep-06 5:57 
GeneralRe: Scrolled Image size Pin
AndrewRansom12-Sep-06 8:48
AndrewRansom12-Sep-06 8:48 
GeneralRe: Scrolled Image size Pin
Rob Brookes12-Sep-06 9:53
Rob Brookes12-Sep-06 9:53 
GeneralRe: Scrolled Image size Pin
Anthony Queen12-Sep-06 11:09
Anthony Queen12-Sep-06 11:09 
GeneralRe: Scrolled Image size Pin
Rob Brookes13-Sep-06 0:20
Rob Brookes13-Sep-06 0:20 
GeneralRe: Scrolled Image size Pin
Anthony Queen13-Sep-06 3:08
Anthony Queen13-Sep-06 3:08 
GeneralRe: Scrolled Image size Pin
Rob Brookes13-Sep-06 3:32
Rob Brookes13-Sep-06 3:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.