Scale Images with Pinch Gesture iOS Tutorial

The UIKit framework provides predefined gesture recognizers that detect common gestures. Gesture recognizers are objects that you attach to a view, which allows the view to respond to actions. In this tutorial we will display an image, which can be scaled up and down with the pinch gesture. This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

For product name, use IOS10ScaleImagesTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

We will need an image to scale, so download the following image, and add the image to the project. Select the Copy items if needed checkbox.

Go to the Storyboard and drag an Image View to the main View. Select the Image View and go to the Attributes Inspector. In the Image View section set the Image field to the downloaded image.

To resize the Image View to the dimensions of the image, select the image then go to the Editor menu and choose Size to Fit Content.

Next, drag a Pinch Gesture Recognizer on top of the Image View, this will attach the pinch gesture to our image. User Interaction is not enabled by default on an Image View, so select the Image View and go to the Attributes Inspector. In the View section enable the User Interface Enabled checkbox.

The Storyboard will look like this.

Open the Assistant editor and make sure the ViewController.swift file is visible next to the Storyboard. Ctrl-drag or right click-drag from the Image View to the ViewController class and create the following Outlet.

When the user starts a pinch gesture we need a callback method to handle the pinch and to alter the image. Ctrl-drag or right click-drag from the Pinch Gesture Recognizer to the ViewController class and create the following Action. Make sure the Type field is changed from Any to UIPinchGestureRecognizer.

Next, implement the scaleImage Action method

@IBAction func scaleImage(_ sender: UIPinchGestureRecognizer) {
    myImageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
}

Every view has a transform that is applied to it, this is information of the rotation,translation and scale that can be applied to the current view.The CGAffineTransform(scaleX:, y:) function is used to scale the view's transform based on the gesture.

Build and Run the project on an iOS device instead of the Simulator, because it is a lot easier to do a pinch gesture on a real device. Try to scale the image back and forth using the pinch gesture.

You can download the source code of the IOS10ScaleImagesTutorial at the ioscreator repository on github.