How to rotate UIImage

后端 未结 10 737
既然无缘
既然无缘 2021-01-03 23:03

I\'m developing an iOS app for iPad. Is there any way to rotate a UIImage 90º and then add it to a UIImageView? I\'ve tried a lot of different codes but none worked...

相关标签:
10条回答
  • 2021-01-03 23:48

    You may rotate UIImageView itself with:

    UIImageView *iv = [[UIImageView alloc] initWithImage:image];
    iv.transform = CGAffineTransformMakeRotation(M_PI_2);
    

    Or if you really want to change image, you may use code from this answer, it works.

    0 讨论(0)
  • 2021-01-03 23:50

    This will rotate an image by any given degrees.

    Note this works 2x and 3x retina as well

    - (UIImage *)imageRotatedByDegrees:(CGFloat)degrees {
        CGFloat radians = DegreesToRadians(degrees);
    
        UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.size.width, self.size.height)];
        CGAffineTransform t = CGAffineTransformMakeRotation(radians);
        rotatedViewBox.transform = t;
        CGSize rotatedSize = rotatedViewBox.frame.size;
    
        UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, [[UIScreen mainScreen] scale]);
        CGContextRef bitmap = UIGraphicsGetCurrentContext();
    
        CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2);
    
        CGContextRotateCTM(bitmap, radians);
    
        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;
    }
    
    0 讨论(0)
  • 2021-01-04 00:01

    Another way of doing this would be to render the UIImage again using Core Graphics.

    Once you have the context, use CGContextRotateCTM.

    More info on this Apple Doc

    0 讨论(0)
  • 2021-01-04 00:02

    Thanks Jason Crocker this solved my problem. Only one minor correction, interchange height and width in both locations and no distortion occurs, ie,

    UIGraphicsBeginImageContext(CGSizeMake(size.width, size.height));
    [[UIImage imageWithCGImage:[sourceImage CGImage] scale:1.0 orientation:clockwise ? UIImageOrientationRight : UIImageOrientationLeft]  drawInRect:CGRectMake(0,0,size.width,size.height)]; 
    

    My problem could not be solved by CGContextRotateCTM, I don't know why. My issue is that I'm transmitting my image to a server and it was alway displayed off by 90 degrees. You can easily test if your images are going to work in the non apple world by copying the image to an MS Office Program that you are running on your mac.

    0 讨论(0)
提交回复
热议问题