How to rotate UIImage

后端 未结 10 850
既然无缘
既然无缘 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:41

    This is what i've done when i wanted to change the orientation of an image (rotate 90 degree clockwise).

    //Checking for the orientation ie, image taken from camera is in portrait or not.
    if(yourImage.imageOrientation==3)
    {
        //Image is in portrait mode.
        yourImage=[self imageToRotate:yourImage RotatedByDegrees:90.0];
    }
    
    - (UIImage *)image:(UIImage *)imageToRotate RotatedByDegrees:(CGFloat)degrees
    {
        CGFloat radians = degrees * (M_PI / 180.0);
    
        UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, image.size.height, image.size.width)];
        CGAffineTransform t = CGAffineTransformMakeRotation(radians);
        rotatedViewBox.transform = t;
        CGSize rotatedSize = rotatedViewBox.frame.size;
    
        UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, [[UIScreen mainScreen] scale]);
        CGContextRef bitmap = UIGraphicsGetCurrentContext();
    
        CGContextTranslateCTM(bitmap, rotatedSize.height / 2, rotatedSize.width / 2);
    
        CGContextRotateCTM(bitmap, radians);
    
        CGContextScaleCTM(bitmap, 1.0, -1.0);
        CGContextDrawImage(bitmap, CGRectMake(-image.size.width / 2, -image.size.height / 2 , image.size.height, image.size.width), image.CGImage );
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    The rotated image may be of size >= 15MB (from my experience). So you should compress it and use it. Otherwise, you may met with crash causing memory pressure. Code I used for compressing is given below.

    NSData *imageData = UIImageJPEGRepresentation(yourImage, 1);
    //1 - it represents the quality of the image.
    NSLog(@"Size of Image(bytes):%d",[imageData length]);
    //Here I used a loop because my requirement was, the image size should be <= 4MB.
    //So put an iteration for more than 1 time upto when the image size is gets <= 4MB.
    for(int loop=0;loop<100;loop++)
    {
        if([imageData length]>=4194304)  //4194304 = 4MB in bytes.
        {
            imageData=UIImageJPEGRepresentation(yourImage, 0.3);
            yourImage=[[UIImage alloc]initWithData:imageData];
        }
        else
        {
            NSLog(@"%d time(s) compressed.",loop);
            break;
        }
    }
    

    Now your yourImage can be used for anywhere.. Happy coding...

提交回复
热议问题