Resize/Scale of an Image – Take 1 – Using an Objective-C Category
November 11, 2009
Editor’s Note: Part 2 of this post Resize/Scale of an Image – Take 2 – Thread Safe Approach takes this idea to the next level, showing how to dynamically resize images using thread safe code.
Given how common it is to scale an image within an application, it’s surprising (at least to me) that such a method is not included in the UIImage class. Let’s go ahead and take care of this omission by adding a simple method which will provide a means to scale an image.
We’ll use an Objective-C category to add a method to the UIImage class. I covered categories in this post. No question, categories are your friend, as they are very handy in cases such as this, where you would like to add functionality to an existing class.
Defining the UIImage Scale Category
To add a method to the UIImage class, there are two steps we need to take care in the interface defintion. First, create an interface definition for UIImage and add a category name inside a set of parenthesis after the interface declaration. Second, create the method declaration. An example follows:
// UIImage+Scale.h @interface UIImage (scale) -(UIImage*)scaleToSize:(CGSize)size; @end |
Implementation UIImage Scale Category
With the interface in place, let’s write the code for the method that will be added to the UIImage class.
// UIImage+Scale.h #import "UIImage+Scale.h" @implementation UIImage (scale) -(UIImage*)scaleToSize:(CGSize)size { // Create a bitmap graphics context // This will also set it as the current context UIGraphicsBeginImageContext(size); // Draw the scaled image in the current context [self drawInRect:CGRectMake(0, 0, size.width, size.height)]; // Create a new image from current context UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); // Pop the current context from the stack UIGraphicsEndImageContext(); // Return our new scaled image return scaledImage; } @end |
Using the UIImage Scale Method
Calling the new scale method we added to UIImage is as simple as this:
#import "UIImage+Scale.h" ... // Create an image UIImage *image = [UIImage imageNamed:@"myImage.png"]; // Scale the image UIImage *scaledImage = [image scaleToSize:CGSizeMake(25.0f, 35.0f)]; |



