Created
October 20, 2009 16:56
-
-
Save runeb/214425 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(UIImage*)imageByScalingToSize:(CGSize)targetSize | |
{ | |
UIImage* sourceImage = self; | |
CGFloat targetWidth = targetSize.width; | |
CGFloat targetHeight = targetSize.height; | |
CGImageRef imageRef = [sourceImage CGImage]; | |
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); | |
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); | |
if (bitmapInfo == kCGImageAlphaNone) { | |
bitmapInfo = kCGImageAlphaNoneSkipLast; | |
} | |
CGContextRef bitmap; | |
if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) { | |
bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); | |
} else { | |
bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); | |
} | |
// In the right or left cases, we need to switch scaledWidth and scaledHeight, | |
// and also the thumbnail point | |
if (sourceImage.imageOrientation == UIImageOrientationLeft) { | |
CGContextRotateCTM (bitmap, radians(90)); | |
CGContextTranslateCTM (bitmap, 0, -targetHeight); | |
} else if (sourceImage.imageOrientation == UIImageOrientationRight) { | |
CGContextRotateCTM (bitmap, radians(-90)); | |
CGContextTranslateCTM (bitmap, -targetWidth, 0); | |
} else if (sourceImage.imageOrientation == UIImageOrientationUp) { | |
// NOTHING | |
} else if (sourceImage.imageOrientation == UIImageOrientationDown) { | |
CGContextTranslateCTM (bitmap, targetWidth, targetHeight); | |
CGContextRotateCTM (bitmap, radians(-180.)); | |
} | |
CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef); | |
CGImageRef ref = CGBitmapContextCreateImage(bitmap); | |
UIImage* newImage = [UIImage imageWithCGImage:ref]; | |
CGContextRelease(bitmap); | |
CGImageRelease(ref); | |
return newImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment