Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate the imageView in a UIButton, and NOT scale it

I am endeavouring to rotate the imageView property of a UIBUtton without scaling it. The image in question is 24x18 - wider than it is tall - but once rotated into place the image is being scaled to keep those dimension - leaving me with a very squished image. How can I prevent this?

Below is my code ..

-(IBAction)rotateButton
{
NSLog( @"Rotating button" );

[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:.5f];
if( CGAffineTransformEqualToTransform( button.imageView.transform, CGAffineTransformIdentity ) )
{
    button.imageView.transform = CGAffineTransformMakeRotation(M_PI/2);
} else {
    button.imageView.transform = CGAffineTransformIdentity;
}
[UIView commitAnimations];
}

This doesn't happen if I apply the transform to the button instead of button.imageView, so I'm guessing it's a property of imageView that I'm not setting right.

Your clues & boos are most welcome

M.

like image 353
Martin Cowie Avatar asked Aug 16 '10 11:08

Martin Cowie


People also ask

How do I rotate UIImageView?

Step 1 − Open Xcode→SingleViewApplication→name it RotateImage. Step 2 − Open Main. storyboard, add UIImageView and add 2 buttons as shown below name them ROTATE BY 90 DEGREES AND ROTATE BY 45 DEGREES.


2 Answers

Apply following code on initialization of view somewhere in view did load. This will help. The answer that you got above is not a true answer :)

button.imageView.clipsToBounds = NO;
button.imageView.contentMode = UIViewContentModeCenter;
like image 179
Nikita Leonov Avatar answered Oct 03 '22 01:10

Nikita Leonov


I've found that subclassing UIButton to remove the transform during layoutSubviews worked, like this:

class RotatableImageButton: UIButton {
    override func layoutSubviews() {
        let originalTransform = imageView?.transform
        imageView?.transform = CGAffineTransformIdentity
        super.layoutSubviews()
        if let originalTransform = originalTransform {
            imageView?.transform = originalTransform
        }
    }
}
like image 28
John Gibb Avatar answered Oct 03 '22 00:10

John Gibb