How to rotate an image 90 degrees on iOS?

后端 未结 14 1854
野的像风
野的像风 2020-11-29 00:55

What I want to do is take a snapshot from my camera , send it to a server and then the server sends me back the image on a viewController. If the image is in portrait mode t

14条回答
  •  醉梦人生
    2020-11-29 01:48

    This is the complete code for rotation of image to any degree just add it to appropriate file ie in .m as below where you want to use the image processing

    for .m

    @interface UIImage (RotationMethods)
    - (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;
    @end
    
    @implementation UIImage (RotationMethods)
    
    static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
    
    - (UIImage *)imageRotatedByDegrees:(CGFloat)degrees 
    {   
        // calculate the size of the rotated view's containing box for our drawing space
        UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
        CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
        rotatedViewBox.transform = t;
        CGSize rotatedSize = rotatedViewBox.frame.size;
    
        // 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;
    
    }
    
    @end
    

    This is the code snippet form apple's SquareCam example.

    To call the above method just use the below code

    UIImage *rotatedSquareImage = [square imageRotatedByDegrees:rotationDegrees];
    

    Here the square is one UIImage and rotationDegrees is one flote ivar to rotate the image that degrees

提交回复
热议问题