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 zpasternack.org. 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;

@end


// 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();
    UIGraphicsEndImageContext(); 

    return scaledImage;
}

@end

No comments:

Post a Comment