So I am working with the iOS 4.2 to add zoom and pan to my application. I have implemented an instance of the UIPinchGestureRecognizer and UIPanGestureRecognizer. It seems to me that only one of these is recognizing a gesture at a time. In particular, the latter only reacts when one finger is down, while the former reacts when the second finger is present. That is okay, but it has some side effects that I think make for inferior quality of user experience.
When you put two fingers down and then move one of them, the image expands (zooms in) like it should, but the pixels under the fingers are no longer under the finger. The image scales from the center of the image, not the mid point between the two fingers. And that center point is itself moving. I want that center point's movement to dictate the panning of the image overall.
Do nearly all iOS applications have this same behavior, where the image zooms in or out around the center of the image rather than the pixels under the fingers tracking the fingers?
It seems to me that creating a custom gesture recognizer is the correct design approach to this problem, but it also seems to me that someone would have created such a recognizer for commercially free download and use. Is there such a UIGestureRecognizer?
Sorry, in a rush but this is the code I used for one of my demo apps, it can pinch zoom and pan at the same time without using scrollview.
Don't forget to conform to UIGestureRecognizerDelegate protocol
If you're not able to get both pinch and pan at the same time, maybe it's because you're missing this method:
Here is the full source code:
So I created the custom gesture recognizer in light of no one giving me a better solution that achieved the desired results. Below are the key code fragments that allow the custom recognizer to indicate where the view should reposition and what its new scale should be with the centroid as the center of the pan and zoom effects so that the pixels under the fingers remain under the fingers at all time, unless the fingers appear to rotate, which is not supported and I can't do anything to stop them from such a gesture. This gesture recognizer pans and zooms simultaneously with two fingers. I need to add support later for one finger panning, even when one of two fingers is lifted up.
The view controller handles the events by assigning the new scale and center to the view in question. I noticed that other gesture recognizers tend to allow the controller to do some of the math, but I tried to do all the math in the recognizer.
The easier solution is to put your view inside a scroll view. Then you get pinch and pan for free. Otherwise, you can set both your pan and pinch gesture delegates to self and return YES for shouldRecognizeSimultaneously. As for zooming into the center of the user's fingers, I never did solve that one correctly but it involves manipulating the
anchorPoint
of your view's layer before changing its scale (I think).