UIImage categories (part 4 of 4)

And the final step of the process is to take the scaled image and center it in a rectangle. Here is the code for that:

- (UIImage *)imageCenteredInSize:(CGSize)newSize
{
    CGSize imageSize = self.size;
    CGFloat x = (newSize.width - imageSize.width) / 2.0;
    CGFloat y = (newSize.height - imageSize.height) / 2.0;
    CGFloat w = imageSize.width;
    CGFloat h = imageSize.height;
    UIGraphicsBeginImageContext(newSize);
    [self drawInRect:CGRectMake(x, y, w, h)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

I believe that I found this code on Stack Overflow.

BTW, Happy Doughnut Day to everyone.

Leave a Reply