如何旋转UIImage?

时间:2015-08-25 17:10:55

标签: ios objective-c uiimage

我想从另一个转换为45°(左下角,顺时针方向)创建一个新的UIImage。旧图像周围的空间将填充为白色左右。在我上传的图像中,旧图像将是蓝色图像,新图像将是我链接的实际图像,包括白色部分。

How I imagine the new image would look

2 个答案:

答案 0 :(得分:0)

如果您只想更改显示图像的方式,请转换显示图像的图像视图。

如果您真的想要一个新的旋转图像,请在变换后的图形上下文中重绘图像。

答案 1 :(得分:0)

如果您只想旋转用于显示图片的UIImageView,您可以这样做:

#define DegreesToRadians(x) ((x) * M_PI / 180.0) //put this at the top of your file
imageView.transform = CGAffineTransformMakeRotation(DegreesToRadians(45));

但是如果要旋转实际图像,请执行以下操作:

- (UIImage *)image:(UIImage *)image rotatedByDegrees:(CGFloat)degrees
{
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.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(-image.size.width / 2, -image.size.height / 2, image.size.width, image.size.height), [image CGImage]);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

以上代码改编自The Lion https://stackoverflow.com/a/11667808/1757960

的回答