In this post we will see how to build “pinch to zoom” functionality to zoom in an image in RubyMotion.
First let’s add a
UIViewController that is initialized with an image.
UIScrollView and UIImageView
Now, we will add a
UIScrollView with frame size set to full screen size and some other properties as listed below.
Create a new
UIImageView and add it to the scrollView created above.
We are setting the image view’s content mode to
UIViewContentModeScaleAspectFit. Content mode can be set to either
UIViewContentModeScaleAspectFit depending on what suits your app. By default,
contentMode property for most views is set to
UIViewContentModeScaleToFill, which causes the view’s contents to be scaled to fit the new frame size. This Apple doc explains this behavior.
We need to add the above imageView as a subview to our scrollView.
This is how our controller looks with all the above additions.
We must set a delegate for our scroll view to support zooming. The delegate object must conform to the
UIScrollViewDelegate protocol. This is the reason we are setting scrollView.delegate = self above. The delegate class must implement
These two methods added above allow the scrollView to support pinch to zoom.
Supporting orientation changes
There is one more thing to do if we want to support orientations changes. We need to add the following methods:
We have to set the scrollView’s frame to view bounds in
viewDidLayoutSubviews so that the scrollView frame is resized when the device orientation changes.
That’s it. With all those changes now our app supports orientation change and now we are able to pinch and zoom images.