How to Rotate a UIImage 90 degrees?

前端 未结 19 878
天涯浪人
天涯浪人 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:05

    Minor change to the other answers that are based on Hardy Macia's code. There is no need to create a whole UIView object simply to calculate the bounding rectangle of the rotated image. Just apply a rotate transform to the image rectangle using CGRectApplyAffineTransform.

    static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;}
    static CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;}
    
    
    - (CGSize)rotatedImageSize:(CGFloat)degrees
    {
        CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
        CGRect originalImageRect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGRect rotatedImageRect = CGRectApplyAffineTransform(originalImageRect, t);
        CGSize rotatedSize = rotatedImageRect.size;
    
        return rotatedSize;
    }
    
    - (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
    {
        // calculate the size of the rotated view's containing box for our drawing space
        CGSize rotatedSize = [self rotatedImageSize:degrees];
    
        // Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize);
        CGContextRef bitmap = UIGraphicsGetCurrentContext();
    
        // Move the origin to the middle of the image so we will rotate and scale around the center.
        CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    
        //   // Rotate the image context
        CGContextRotateCTM(bitmap, DegreesToRadians(degrees));
    
        // Now, draw the rotated/scaled image into the context
        CGContextScaleCTM(bitmap, 1.0, -1.0);
        CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
    
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    

提交回复
热议问题