Azhar
Azhar

Reputation: 20670

Swift: How to get Height and width of a rotated image.

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

Upvotes: 2

Views: 1248

Answers (2)

Azhar
Azhar

Reputation: 20670

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.

Upvotes: 2

user9557173
user9557173

Reputation:

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

Upvotes: 0

Related Questions