Monday, February 14, 2011

Why Didn't It Come With This? Part 1

Note: This blog is deprecated. @synthesize zach has moved to a new home, at This blog entry can be found on the new blog here. Please update your links.

Sometimes I find myself writing the same function over and over, and I wonder, "Why didn't it come with this?" Here's one I did today. I have a UIImage which I want to scale to a different size. Actually, this happens in 3 or 4 places in PuzzleTiles. I finally broke down and made it a category on UIImage. Hopefully you find it useful as well.

// UIImage+Resizing.h

@interface UIImage (Resizing)

- (UIImage*) scaledImageWithSize:(CGSize)newSize;


// UIImage+Resizing.m

#import "UIImage+Resizing.h"

@implementation UIImage (Resizing)

- (UIImage*) scaledImageWithSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions( newSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, newSize.width, newSize.height );
    [self drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    return scaledImage;


No comments:

Post a Comment