0
votes

I have a UIImageView and I am applying a rotation transform using CGAffineTransformMakeRotation. This does not only rotate the image but scales it as well.

What is the correct way to rotate a UIImageView and retain the size/scale of the image?

I tried setting

self.image.contentMode = UIViewContentModeCenter;
self.image.autoresizingMask = UIViewAutoresizingNone;

and it doesn't seem to help.

1
Rotation transform doesn't scale the image. There must be some other problem with your code. Are you using storyboards to create the UIImageView? Try to narrow it by commenting out references to the object or try to create a small sample project reproducing the problemmaroux
I create the UIImageView in code and I apply a transform to it. After reading around here the issue is that the rotated view tries to fit the image into it and stretches it. There are some solutions using IB, but I am doing it in code.some_id
@Mar0ux - I have just created a basic UIView with a UIImageView rendered in its drawRect method using drawInRect.some_id
Are you drawing the image yourself using drawInRect? If so, you need to apply the transform to the CGContextRef. Also, be aware that UIView's frame property isn't valid after applying a transform.maroux
Yes I am drawing them using drawInRect. I pass in the frame which you say is invalid. It renders, just scaled. What frame is it using? I apply the transform to the context. I have 3 images that scale and rotate independently and are stacked on top of one another. I cannot apply the transform to the entire context.some_id

1 Answers

0
votes

try the below method

-(UIImage*)rotateImage:(UIImage*)img forAngle:(CGFloat)radian   {

    UIView *rotatedViewBox = [[UIView alloc]initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(radian);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    UIGraphicsBeginImageContext(rotatedSize);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, rotatedSize.width, rotatedSize.height);
    CGContextRotateCTM(context, radian);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(-img.size.width, -img.size.height, img.size.width, img.size.height), img.CGImage);
    UIImage *returnImg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return returnImg;
}