Rotate Image iOS Tutorial

The Core Animation framework makes it possible to perform all type animations on a view, including rotation. In this tutorial an image will be rotated. This tutorial is made with Xcode 8.3 and built for iOS 10.3.

Open Xcode and create a new Single View Application.

For product name, use IOS10RotateImageTutorial 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.

Go to the Storyboard. Add an Image View from the Object Library to the main view and go to the Size Inspector. Enter the following values to position the Image View.

Select the Image View and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Image View and select the Auto Layout pin button. Pin the label to the top and select the Width and Height checkboxes. Click "Add 3 Constraints".

Download the zip file containing the image. Extract it and add the file to the project. Make sure you check the "Copy items if needed" checkbox.

Drag a Button to the main view and place it below the Image View. Give it a title of "Rotate". Select the button and Ctrl + drag to the Image View. Hold down the Ctrl button and select "Vertical Spacing" and "Center Horizontally".

The Storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Image View to the ViewController class and create the following Outlet.

Ctrl + drag from the Rotate button to the ViewController class and create the following Action.

Go to the ViewController.swift file and implement the rotateImage method.

@IBAction func rotateImage(_ sender: Any) {
    UIView.animate(withDuration: 2.0, animations: {
        self.imageView.transform = CGAffineTransform(rotationAngle: (180.0 * .pi) / 180.0)

The image will rotate 180 degrees using the CGAffineTranform function. Build and Run the project and tap the Rotate Button to rotate the image.

You can download the source code of the IOS10RotateImageTutorial at the ioscreator repository on Github