Restricted Pan and Zoom in WPF
After running into animation problems in Silverlight 3 and 4, I?m implementing my user interface using full blown WPF. This Pan and Zoom code works great, with a minor tweak and one issue: I need to control the allowable zoom ranges, and I don?t want the user to be able to pan the image ?right off of the map?, instead I need a hard border on all four sides. And these hard-stops need to pay attention to the current zoom level as well.
Minimum and Maximum Zoom
This part is easy ? I added two properties, MinimumZoom and MaximumZoom, default them to double.MinValue and double.MaxValue, and some trivial code in DoZoom to keep the scale values in line:
Limiting Pan Transform
This required slightly more thought, and some graph paper. Having a clue about how WPF deals with its coordinate systems would have been helpful too. I have a Canvas as the Content of my PanAndZoomViewer. No matter what panning & zooming happens, this Canvas will always have a fixed Height and Width. The Origin in our setup is always going to be the upper left corner of the Canvas, and remember that in the coordinate system used by Windows, ?up? and ?left? from that point are negative values. (The Y axis is the opposite of what you?d expect). Here?s a lame Paint.NET picture to help you understand:
The Red View area is the part of the map canvas you?re zoomed into and viewing. The blue area is the entire map. I don?t want you to be able to move the Red rectangle beyond the boundaries of the Blue Rectangle, because instead of viewing the map you?d be viewing the dining room table, or the Red Rectangle would fall off the table onto the floor, or something.
Handling the Left and Top boundaries of the Blue Rectangle are easy enough, at any zoom level. If you were to move the Red Rectangle to beyond either of those edges, then one or both of the values for (ToX, ToY) would be positive (past the Origin corner). So we reset positive values back to zero and then animate to keep things nice and smooth.
Pan Right, Bottom
The other two edges are slightly less intuitive, at least to me. Consider the Right edge of the Red Rectangle View: I don?t want this edge passing over the Blue Rectangle. This puts a ?maximum? value on the distance from the Left Edge of the Red Rectangle (at X = 0), and the Left Edge of the Blue Rectangle. Except that this value would be negative being to the left of the origin, so it?s really a minimum. (Trivial arithmetic, I know, and yet I still messed it up the first time.)
So, the minimum allowed ToX value is content.Width – (content.Width * scale). If you try to move the Red Rectangle farther away, we just snap it back to the edge. Same thing with the minimum Y values.
The code to handle this looks something like this: