2013 이전/iOS개발

[iPhone 개발] CGImage의 Orientation

하구루 2017. 2. 25. 16:05

UIImage 의 CGImage를  Quartz 2D를 통해 그리다 보면 UIImage를 통해서 그릴때와 다르게

Orientation이 제대로 적용이 안되게 될것이다.
섬네일을 만들기 위해서 이미지를 일정 크기로 축소를 하다가 발견한 것인데,
 
UIImage에는 imageOrientation라는  property orientation 정보가 들어 있고, 그 정보를 통해서 CGImage를 회전하여 보여주게된다.
즉, CGImage 자체는 Orientation이 적용되지 않은 순수한 이미지 정보인것이다.
때문에 CGImage를 이용할때 UIImage의 imageOrientation정보를 이용해 변경 해야한다.
imageOrientaion의 데이터 형은 다음과 같다 .
typedef enum {
   UIImageOrientationUp,
   UIImageOrientationDown,   // 180 deg rotation
   UIImageOrientationLeft,   // 90 deg CCW
   UIImageOrientationRight,   // 90 deg CW
   UIImageOrientationUpMirrored,    // as above but image mirrored along
   // other axis. horizontal flip
   UIImageOrientationDownMirrored,  // horizontal flip
   UIImageOrientationLeftMirrored,  // vertical flip
   UIImageOrientationRightMirrored, // vertical flip
} UIImageOrientation;

그리고 다음은 본인이 이용하기위해 UIImage와 줄이려는 이미지 사이즈를 통해 orientation이 적용된 CGImage로 만들어진 순수한 UIImage를 리턴하는 메소드 이다.

-(UIImage*) imageWithOrientationInCGImage:(UIImage* )image withSize:(CGSize)imageNewSize{
    
    UIImageOrientation imageOrientation = image.imageOrientation;
    
    UIImage* resultImage;
    UIGraphicsBeginImageContext(CGSizeMake(imageNewSize.width, imageNewSize.height));
    CGContextRef context = UIGraphicsGetCurrentContext();
    switch (imageOrientation) {
        case  UIImageOrientationUp:
            CGContextTranslateCTM(context, 0, imageNewSize.height);
            CGContextScaleCTM(context, 1.0, -1.0);
            CGContextDrawImage(context, CGRectMake(0, 0, imageNewSize.width, imageNewSize.height), image.CGImage);
            break;
        case UIImageOrientationDown:
            CGContextDrawImage(context, CGRectMake(0, 0, imageNewSize.width, imageNewSize.height), image.CGImage);
            break;
        case UIImageOrientationLeft:
            CGContextTranslateCTM(context, imageNewSize.width, 0);
            CGContextScaleCTM(context, -1.0, 1.0);
            CGContextTranslateCTM(context, 0, imageNewSize.height);
            CGContextRotateCTM (context, -90 * M_PI / 180);
            CGContextDrawImage(context, CGRectMake(0, 0, imageNewSize.height, imageNewSize.width), image.CGImage);
            break;
        case UIImageOrientationRight:
            CGContextTranslateCTM(context, imageNewSize.width, 0);
            CGContextScaleCTM(context, -1.0, 1.0);
            CGContextTranslateCTM(context, imageNewSize.width, 0);
            CGContextRotateCTM (context, 90 * M_PI / 180);
            CGContextDrawImage(context, CGRectMake(0, 0, imageNewSize.height, imageNewSize.width), image.CGImage);
            break;
        default:
            
            break;
    }

    resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImage;
}

UIImage에 있는 imageOrientation을 확인해서 CGImage를 변경하여 새로운 UIImage에 넣어주는 방식이다.

반응형