Wednesday, June 8, 2011

Merge image function

Here's a simple method in a UIImage category that I'm using to merge two images together. It's based mostly on the code here but is cleaned up and allows a few options.

UIImage+Utils.m

// NOTE! this method should only be called from the main thread because of
// UIGraphicsGetImageFromCurrentImageContext();
- (UIImage *)merge:(UIImage *)image atRect:(CGRect)pos overlay:(BOOL)overlay;
{
        UIGraphicsBeginImageContext(self.size);
        
        UIImage *bottom = (overlay)?self:image;
        UIImage *top = (overlay)?image:self;
        
        CGRect lf = CGRectMake(0, 0, self.size.width, self.size.height);
        
        CGRect bottomRect = (overlay)?lf:pos;
        CGRect topRect = (overlay)?pos:lf;
        
        [bottom drawInRect:bottomRect];
        [top drawInRect:topRect];

        UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();    
        UIGraphicsEndImageContext();
        return destImage;        
}

No comments:

Post a Comment