어젯밤 UIImage Rotation 을 구글링하다
마땅히 찾지 못해서;;
일단 급하게 만들어봄..
Rotation하면 크기가 커지기 마련인데;;
그냥 UIImageView transform하듯이 하려면
중간에 주석을 제거하면 된다.
/**
* UIImage + Rotation
* angle in radian
* @hytgbn
*/
- (UIImage *)rotateImage:(UIImage *)image angle:(CGFloat)rad{
CGImageRef imageRef = [image CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGColorSpaceCreateDeviceRGB();
if (alphaInfo == kCGImageAlphaNone)
alphaInfo = kCGImageAlphaNoneSkipLast;
// original image size
CGFloat width, height;
width = [image size].width;
height = [image size].height;
// this kind of a dull stuff, looking for better looking-good code..
CGFloat newWidthMax = max( 0.f*cos(rad)+0.f*sin(rad) ,
max( width*cos(rad)+height*sin(rad) ,
max( 0.f*cos(rad)+height*sin(rad) ,
width*cos(rad)+0.f*sin(rad) )));
CGFloat newWidthMin = min( 0.f*cos(rad)+0.f*sin(rad) ,
min( width*cos(rad)+height*sin(rad) ,
min( 0.f*cos(rad)+height*sin(rad) ,
width*cos(rad)+0.f*sin(rad) )));
CGFloat newHeightMax = max( -0.f*sin(rad)+0.f*cos(rad) ,
max( -width*sin(rad)+height*cos(rad) ,
max( -0.f*sin(rad)+height*cos(rad) ,
-width*sin(rad)+0.f*cos(rad) )));
CGFloat newHeightMin = min( -0.f*sin(rad)+0.f*cos(rad) ,
min( -width*sin(rad)+height*cos(rad) ,
min( -0.f*sin(rad)+height*cos(rad) ,
-width*sin(rad)+0.f*cos(rad) )));
CGFloat newWidth = newWidthMax - newWidthMin;
CGFloat newHeight = newHeightMax - newHeightMin;
// and if you want to rotate into same size, uncomment 2 lines
// newWidth = width;
// newHeight = height;
DLog(@"original : %f, %f", width, height);
DLog(@"new : %f, %f", newWidth, newHeight);
CGContextRef bitmap;
bitmap = CGBitmapContextCreate(NULL, (int)newWidth, (int)newHeight,
CGImageGetBitsPerComponent(imageRef),0, colorSpaceInfo, alphaInfo);
CGContextTranslateCTM (bitmap, newWidth/2.f,newHeight/2.f);
CGContextRotateCTM (bitmap, rad);
CGContextTranslateCTM (bitmap, -width/2.f,-height/2.f);
CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage *result = [UIImage imageWithCGImage:ref];
CGContextRelease(bitmap);
CGImageRelease(ref);
return result;
}