How to Rotate a UIImage 90 degrees?

前端 未结 19 1255
天涯浪人
天涯浪人 2020-11-22 08:45

I have a UIImage that is UIImageOrientationUp (portrait) that I would like to rotate counter-clockwise by 90 degrees (to landscape). I don\'t want

19条回答
  •  深忆病人
    2020-11-22 09:00

    I like the simple elegance of Peter Sarnowski's answer, but it can cause problems when you can't rely on EXIF metadata and the like. In situations where you need to rotate the actual image data I would recommend something like this:

    - (UIImage *)rotateImage:(UIImage *) img
    {
        CGSize imgSize = [img size];
        UIGraphicsBeginImageContext(imgSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextRotateCTM(context, M_PI_2);
        CGContextTranslateCTM(context, 0, -640);
        [img drawInRect:CGRectMake(0, 0, imgSize.height, imgSize.width)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    

    The above code takes an image whose orientation is Landscape (can't remember if it's Landscape Left or Landscape Right) and rotates it into Portrait. It is an example which can be modified for your needs.

    The key arguments you would have to play with are CGContextRotateCTM(context, M_PI_2) where you decide how much you want to rotate by, but then you have to make sure the picture still draws on the screen using CGContextTranslateCTM(context, 0, -640). This last part is quite important to make sure you see the image and not a blank screen.

    For more info check out the source.

提交回复
热议问题