How to rotate UIImage

后端 未结 10 727
既然无缘
既然无缘 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: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;
    }
    

提交回复
热议问题