0

I would like to use a pinch gesture to change the size of the image. With the code shown below I achieve that, but every time I pinch the picture after that, the image bounces back to the original size.

@IBAction func pinchGestureActivated(_ sender: UIPinchGestureRecognizer) {
    imageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
}
JillevdW
  • 1,087
  • 1
  • 10
  • 21
Patrick
  • 1
  • 2
  • Is this the only code that transform the imageView in your project? – Kerberos Aug 01 '18 at 08:25
  • using `imageView.transform` only changes the scale or size of the imageView UI component, not the image itself. The imageView is just an image container. Take a look at other answers already on here – Scriptable Aug 01 '18 at 08:52
  • Possible duplicate of [How to Resize image in Swift?](https://stackoverflow.com/questions/31314412/how-to-resize-image-in-swift) – Scriptable Aug 01 '18 at 08:52

1 Answers1

0

This is what is happening:

  • Your imageView is 100 x 100.
  • You pinch it, it goes down to 20 x 20.
  • Pinch ends. // Your imageView size hasn't changed. It has just been transformed. None of the changes reflect on it.
  • You pinch again. // The imageView is still 100 x 100. So the transformation takes place again from 100 x 100.

When the transform property of any UIView subclass is not set to the identity, the frame won't actually be changed, and that is probably the reason you're observing this. We can work with that:

@IBAction func pinchGestureActivated(_ sender: UIPinchGestureRecognizer) {
    imageView.transform = imageView.transform.scaledBy(x: sender.scale, y: sender.scale)
}

This should do the job :)

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
JillevdW
  • 1,087
  • 1
  • 10
  • 21