Search code examples
iosswift3uiimageviewrotationcgaffinetransform

Swift 3: Image returns to its original size or transform after rotation


I have image view the large image inside, as I rotate it using
CGAffineTransform() , it is rescaled to its original transform or size, still can't figure that out yet.

Needed working scenario is:

I want to have an image view scaled to %35 of its original size, then be able to rotate it programmatically without changed its size. How can I achieve that?

EDIT:

Full scenario is, I have Large Imageview (let's call it main) with image view mentioned above (sub) as its subview.

I scale (main) by 0.5 which scales (sub) too, and after that I scale (sub) by 0.35, so when I rotate it is hard to scale every time. that is why I want a way to rotate without scaling again.


Solution

  • let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    var t = CGAffineTransform.identity
    t = t.scaledBy(x: 0.35, y: 0.35)//35% of size
    //You can change alter this t value any way you want.
    t = t.rotated(by: CGFloat.pi / 4)//Random value, change to your wanted value
    //And then just set it
    imageView.transform = t
    

    EDIT: This code works. Retested it now. You sure you are using it correctly? Just ran tested it now.

    var t = CGAffineTransform.identity
    var imageView = UIImageView()
    
    func scaleImage() {
        t = t.scaledBy(x: 0.35, y: 0.35)//35% of size
        imageView.transform = t
    }
    func rotateImage() {
        t = t.rotated(by: CGFloat.pi / 4)//Random value, change to your wanted value
        imageView.transform = t
    }