Thursday, February 23, 2012

Nice panning and zooming in Windows Phone 7

A bit of time ago I published an app called Hidden Pics on the Microsoft Marketplace, on that entry I covered some basics on the Isolated Storage and the PhotoChooserTask for Windows Phone 7. On this entry I want to cover the zooming and panning. As part of that app, the user has the option to open a photo full size on the device screen and then pinch to zoom the photo.  They can also pan by dragging on the screen with the fingers.

Now this is supposed to be very basic, but there is a catch, which is making the zoom stable. By stable I mean that if you use two fingers to zoom in the photo, once you finish the two fingers should have the same pixels behind them, which indicates that you zoomed proportionally and panned correctly. After googling around a bit I put together the code to do both zooming and panning properly.

So here is the XAML for the control, I am using an Image control inside a Canvas with a CompositeTransform:



The photo will start fully fitted on the Image control, and in this case my app starts in portrait. Now the event is hooked for flicks (I use them to switch from one photo to the next one) and the PinchDelta and PinchStarted events are the ones we will use here. Now check the code and see how it is done.



Now notice the OrientationChanged event of the Silverlight page is here, the reason is that I want the user to be able to use the zoom and panning either in portrait or landscape mode, but for that, I do really need Width and Height of the Image control to be set. Also I check if the scale is 1 or less, then in that case the ApplicationBar is shown and the image is fit to the screen. So if the photo is not zoomed, a flick will move to the next or previous photo, but then the photo is zoomed, no menu and and flicking will just pan around the photo. See the code for the flick event:



Hope you can make use of this.

No comments: