We can drag and scale an UIImageView over another UIImageView using two gestures :
UIPanGestureRecognizer and UIPinchGestureRecognizer.
For Dragging an Image View : UIPanGestureRecognizer
For Scaling an Image View : UIPinchGestureRecognizer
Here is my view that looks like : Click here —— >
Take two images :
outerImgView in background with Content mode as AspectFit
innerImgView in background with Content mode as AspectFit
1 2 |
@IBOutlet weak var outerImgView: UIImageView! @IBOutlet weak var innerImgView: UIImageView! |
Apply UIPanGestureRecognizer over innerImgView as :
1 |
var panGesture = UIPanGestureRecognizer() |
1 2 3 4 |
//pan gesture for dragging an image panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.dragImg(_:))) innerImgView.isUserInteractionEnabled = true innerImgView.addGestureRecognizer(panGesture) |
dragImg func definition :
1 2 3 4 5 |
@objc func dragImg(_ sender:UIPanGestureRecognizer){ let translation = sender.translation(in: self.view) innerImgView.center = CGPoint(x: innerImgView.center.x + translation.x, y: innerImgView.center.y + translation.y) sender.setTranslation(CGPoint.zero, in: self.view) } |
Apply UIPinchGestureRecognizer over innerImgView as :
1 2 3 4 |
//Pinch Gesture for zoom in and zoom out @IBAction func scaleImg(_ sender: UIPinchGestureRecognizer) { innerImgView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale) } |
I hope from this, it will make you more comfortable using Draggable and Scalable functionality into your app for developing various different features. Thanks for tuning in once again!