【发布时间】:2012-05-19 16:02:12
【问题描述】:
我有一个从 UIImagePickerController 获取的 UIImage。当我从- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 方法收到图像时,我将其直接放入 UIImageView 中进行预览,并为用户提供保存或丢弃图像的选项。
当用户选择保存选项时,应用程序会获取图像的 png 数据并将其保存到它的文档目录中。但是在两种可能的设备方向之一(仅限横向)下发生的情况是图像被颠倒保存(更具体地说,从它应该的位置旋转 180 度)。因此,当我在图库中加载图像时,它会出现颠倒。
(见图库左下角的图片)
我已经解决了这个问题,来自 UIImagePickerController 的 UIImage 中的原始图像数据不会旋转,而是将方向作为属性存储在对象上,并且仅在显示时应用。所以我正在尝试使用我在网上找到的一些代码来旋转与 UIImage 关联的 CGImage。但它似乎对图像完全没有影响。我使用的代码如下:
- (void)rotateImage:(UIImage*)image byRadians:(CGFloat)rads
{
// 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(rads);
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 you want to rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// Rotate the image context
CGContextRotateCTM(bitmap, rads);
// 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]);
image = UIGraphicsGetImageFromCurrentImageContext();
image = [UIImage imageWithCGImage:image.CGImage scale:1.0 orientation:UIImageOrientationDown];
UIGraphicsEndImageContext();
}
我想知道为什么这段代码不起作用,因为我在网上找到的每段代码都可以进行图像旋转。
【问题讨论】:
标签: objective-c ios uiimage cgimage