Tip

Panning and zooming in WPF

Showing an image to the user in WPF is trivial, just use the image element and specify a valid source location for the image file. In certain situations you might want to permit the user to interact with the image. For example, a popular feature in some applications allows a user to move the image around on the screen with the mouse or to zoom in to the picture to see more detail. Adding panning and zooming to your application is a little more work but it's a nice feature to add to your application.

Clipping the image
What should happen when you enlarge the image on the screen? In most circumstances the image should be constrained to a region of the application UI. As you zoom into the picture it stays within that region. In WPF we can accomplish this with a clipping region. Certain elements like the Border expose a ClipToBounds property which makes this task even easier.

Here is a section of the XAML which defines our interface.

As you can see the ClipToBounds property is enabled on the border. The image is nested inside the border which permits the border to clip off the edges of the picture. Notice also the RenderTransform I've applied to the image. I am going to use the ScaleTransform to perform the zoom and the TranslateTransform to manipulate the image while panning. I gave both these transforms a name to make it easier to manipulate them in the code behind.

The Mouse events
I'll use the mouse wheel event to determine when to zoom the picture.

For the panning I'll work with three mouse events; MouseLeftButtonDown, MouseLeftButtonUp and MouseMove.

I'll define two point variables to use during the move.

Then it is simply a matter of setting up the three mouse events as follows:

Application Screenshots

Photo for article is from Yngve Lundström Photography.


This was first published in July 2010

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.