2

I am rotating a square image View whose width is 160 but after rotation width become 190 same as height.

Rotating it by this function

func transformUsingRecognizer(_ recognizer: UIGestureRecognizer, transform: CGAffineTransform) -> CGAffineTransform {

        if let rotateRecognizer = recognizer as? UIRotationGestureRecognizer {
            return transform.rotated(by: rotateRecognizer.rotation)
        }
       return transform
}

tried these two codes to get correct width

imgDraggingImage.bounds.size.width
imgDraggingImage.frame.height

but no success.

Image before rotation width 160

enter image description here

Image after rotation, no change in width but now returning width 190

enter image description here

Seems width value depends on rotation as on any different angle it returns different width value. But I need correct value which in this case is 160. please help

Azhar
  • 20,500
  • 38
  • 146
  • 211

2 Answers2

2
extension CGAffineTransform {
    var angle: CGFloat { return atan2(-self.c, self.a) }

    var angleInDegrees: CGFloat { return self.angle * 180 / .pi }

    var scaleX: CGFloat {
        let angle = self.angle
        return self.a * cos(angle) - self.c * sin(angle)
    }

    var scaleY: CGFloat {
        let angle = self.angle
        return self.d * cos(angle) + self.b * sin(angle)
    }
}

The above extension solve the problem.

  self.imgDraggingImage.transform.scaleX
  self.imgDraggingImage.transform.scaleY

the above code scaleX gave change in Width of image (scale) even if rotated too and scaleY provide the % change in image height.

where imgDraggingImage.bounds.size.width gave constant image size even if image scaled.

while imgDraggingImage.frame.width was creating issue when image was rotated.

Azhar
  • 20,500
  • 38
  • 146
  • 211
  • This works great, could you give an explanation of the maths behind it? I've forgotten my school maths! – Tometoyou Oct 08 '20 at 17:28
0

Depends, do you want the size in Pixels or in Points:

let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale

let widthInPoints = image.size.width
let widthInPixels = widthInPoints * image.scale