How Can I Rotate A UIImage and Image Data By 90 Degrees

前端 未结 6 670
难免孤独
难免孤独 2021-02-09 16:09

I have a UIImageView that contains an image. At the minute the user can click to save the image within the UIImageView to disk.

I would like to make it so that the the

6条回答
  •  余生分开走
    2021-02-09 16:47

    This will rotate an image by any given radians.

    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;
    }
    

提交回复
热议问题