I am trying to resize a CGImageRef so I can draw it on screen with the size I want. So I have this code:
CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);
CGContextRef context = CGBitmapContextCreate(NULL,
CGImageGetWidth(originalImage),
CGImageGetHeight(originalImage),
CGImageGetBitsPerComponent(originalImage),
CGImageGetBytesPerRow(originalImage),
colorspace,
CGImageGetAlphaInfo(originalImage));
if(context == NULL)
return nil;
CGRect clippedRect = CGRectMake(CGContextGetClipBoundingBox(context).origin.x,
CGContextGetClipBoundingBox(context).origin.y,
toWidth,
toHeight);
CGContextClipToRect(context, clippedRect);
// draw image to context
CGContextDrawImage(context, clippedRect, originalImage);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
So this code allows me to apparently draw the image to the size I want, and that's good. The problem is that the actual image I'm getting once resized even though it looks resized on the screen it is not actually resized. When I do:
CGImageGetWidth(imgRef);
It actually returns the original width of the image and not the width that I see on screen.
So how can I actually create an image that is actually resized and not only drawn the right size I want??
Thanks
The issue is that you're creating the context with the same size as the image. You want to make the context the new size. And then clipping is unnecessary.
Try this:
CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);
CGContextRef context = CGBitmapContextCreate(NULL,
toWidth, // Changed this
toHeight, // Changed this
CGImageGetBitsPerComponent(originalImage),
CGImageGetBytesPerRow(originalImage)/CGImageGetWidth(originalImage)*toWidth, // Changed this
colorspace,
CGImageGetAlphaInfo(originalImage));
if(context == NULL)
return nil;
// Removed clipping code
// draw image to context
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), originalImage);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
I didn't actually test it, but it should at least give you the idea of what needs to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With