Thursday, 10 November 2011

Combine two UIImages

To add two UIImages together you need to make use of Graphics Context.

  1. - (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {  
  2.     UIGraphicsBeginImageContext(image1.size);  
  3.   
  4.     // Draw image1  
  5.     [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];  
  6.   
  7.     // Draw image2  
  8.     [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];  
  9.   
  10.     UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();  
  11.   
  12.     UIGraphicsEndImageContext();  
  13.   
  14.     return resultingImage;  
  15. }  

Create a UIImage from a part of another UIImage

This requires a round-trip to Core Graphics land:

  1. - (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {  
  2.     CGImageRef sourceImageRef = [image CGImage];  
  3.     CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);  
  4.     UIImage *newImage = [UIImage imageWithCGImage:newImageRef];  
  5.     CGImageRelease(newImageRef);  
  6.     return newImage;  
  7. }  

Save UIImage to Photo Album

This is just a one-liner:
  1. UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), context);  
And to know if the save was successful:

  1. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {  
  2.     NSString *message;  
  3.     NSString *title;  
  4.     if (!error) {  
  5.         title = NSLocalizedString(@"SaveSuccessTitle", @"");  
  6.         message = NSLocalizedString(@"SaveSuccessMessage", @"");  
  7.     } else {  
  8.         title = NSLocalizedString(@"SaveFailedTitle", @"");  
  9.         message = [error description];  
  10.     }  
  11.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title  
  12.                                                     message:message  
  13.                                                    delegate:nil  
  14.                                           cancelButtonTitle:NSLocalizedString(@"ButtonOK", @"")  
  15.                                           otherButtonTitles:nil];  
  16.     [alert show];  
  17.     [alert release];  
  18. }  

No comments:

Post a Comment