本文转载至 http://stackoverflow.com/questions/8915630/ios-uiimageview-how-to-handle-uiimage-image-orientation
|
Is it possible to setup UIImageView to handle image orientation? When I set the UIImageView to image with orientation RIGHT (it is photo from camera roll), the image is rotated to right, but I want to show it in proper orientation, as it was taken.
I know I can rotate image data but it is possible to do it more elegant?
Thank you
|
asked Jan 18 '12 at 18:49
|
|
|
|
|
If I understand, what you want to do is disregard the orientation of the UIImage? If so then you could do this:
UIImage *originalImage = [... whatever ...];
UIImage *imageToDisplay =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:1.0
orientation: UIImageOrientationUp];
So you're creating a new UIImage with the same pixel data as the original (referenced via its CGImage property) but you're specifying an orientation that doesn't rotate the data.
|
answered Jan 18 '12 at 19:05
|
|
|
|
|
As Anomie suggests in their answer here, this code will help to fix orientation:
- (UIImage *)fixrotation:(UIImage *)image{
if (image.imageOrientation == UIImageOrientationUp) return image;
CGAffineTransform transform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, image.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
break;
}
switch (image.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
|
CGContext
withCGBitmapContextCreate
(or with theUIGraphicsBeginImageContext
shorthand), useCGContextRotateCTM
to set a rotation, use eitherdrawInRect:
on theUIImage
orCGContextDrawImage
with the image'sCGImage
property, then convert the context to an image either withUIGraphicsGetImageFromCurrentImageContext
(and, then,UIGraphicsEndImageContext
) if you used UIKit to create the context, orCGBitmapContextCreateImage
if you were sticking with the Core Graphics. UIKit isn't very thread safe, but the code would be neater. – Tommy Mar 8 '12 at 20:31