综合技术

Scale Image with Pinch Gesture iOS Tutorial

微信扫一扫,分享到朋友圈

Scale Image with Pinch Gesture iOS Tutorial
0

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 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSScaleImageTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

We will need an image to scale, so download the followingimage, and move the image to the Assets folder in the project.

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 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) {
    imageView.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 Runthe 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 IOSScaleImagesTutorial at the ioscreator repository on github .

阅读原文...


iOScreator

Create components like React, using only functions and hooks but in only 2.7kB

上一篇

2019’s Hottest, and Most Bankable, Security Certs

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Scale Image with Pinch Gesture iOS Tutorial

长按储存图像,分享给朋友