3

I have an Image inside UIScrollView which i can zoom in and out. I have a button that let the user rotate the Image 90 degrees:

(void)RotateImage {
    CGAffineTransform rotateTrans = CGAffineTransformMakeRotation(-90.0 / 180.0 * 3.14);
    BaseImg.transform = rotateTrans;
}

After the imaged is rotated i cannot zoom in and out.. the image is going crazy on the screen and going back to the UNRotated state.

What am i doing wrong? code examples will be great! Thanks :)

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • You have to apply the scale transform to the previous rotation transform – Otium Apr 09 '12 at 01:23
  • Two pieces of housekeeping: Instead of `3.14`, use `M_PI`, defined in math.h. This is the closest floating point approximation to pi. And, Objective-C naming conventions start method and variable names with lower-case. So, RotateImage (a method) should be rotateImage, and BaseImg (a variable) should be baseImg. – Cowirrie Apr 09 '12 at 01:50

2 Answers2

1

UIScrollView likes to take over the transforms of the views it contains. There are two solutions:

  1. Rotate the image without changing the containing view.
  2. Create a UIView subclass that displays an image within a sublayer.

To rotate the image, see How to Rotate a UIImage 90 degrees?. If you're always and only doing 90 degree rotation, see @Peter Sarnowski's solution. To adapt it to what you're doing here, assuming that BaseImg is a UIImageView:

- (void) rotateImage
{
    UIImage *sourceImage = [baseImg image];
    UIImage *rotatedImage = [UIImage imageWithCGImage:[sourceImage CGImage] scale:1.0 orientation:UIImageOrientationRight];
    [baseImg setImage:rotatedImage];
}

This will only rotate once. To have rotateImage work repeatedly, read the existing orientation property and move it on to the next in clockwise or anticlockwise order.

If the image is not square, you may also need to resize baseImg to reflect its new aspect ratio.

To create a UIView subclass, you need to have it store a CALayer as a sublayer of the view layer. Store the image in the sublayer, and transform the sublayer at will. This is faster, and allows arbitrary rotation, but you need to calculate your own scaling to prevent the rotate image going outside the view bounds.

Community
  • 1
  • 1
Cowirrie
  • 7,218
  • 1
  • 29
  • 42
  • If this answer was sufficient, please mark it as accepted. This doesn't just increase my [reputation](http://stackoverflow.com/faq#reputation) - it helps other visitors to this site. This applies to all 5 of the questions you have currently asked. – Cowirrie Apr 09 '12 at 22:31
0

To simply rotate image the code is perfect but to add zoom in and out and then add rotation you need to retain its transforms.Here is a sample code that can help you.

https://github.com/elc/iCodeBlogDemoPhotoBoard

Leena
  • 2,678
  • 1
  • 30
  • 43