elio.d elio.d - 2 years ago 161
iOS Question

iOS - Merging two images of different size

I'm facing the following problem : I have to merge two images A and B to create a new image C as a result of the merging.

I already know how to merge two images but in this case my goal is a little bit different.

I would like that image A will be the background for Image B.

For instance if image A size is 500x500 and image B size is 460x460 I would like that image C (the image result of the merging) will be 500x500, with image B (460x460) centered in it.

Thanks in advance for any help or suggestion

Answer Source

This is what I've done in my app, but without using UIImageView:

UIImage *bottomImage = [UIImage imageNamed:@"bottom.png"]; //background image
UIImage *image       = [UIImage imageNamed:@"top.png"]; //foreground image

CGSize newSize = CGSizeMake(width, height);
UIGraphicsBeginImageContext( newSize );

// Use existing opacity as is
[bottomImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

// Apply supplied opacity if applicable
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:0.8];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();


If the image already has opacity, you do not need to set it (as in bottomImage) otherwise you can set it (as with image).

After this UIImage is created then you can embed it in your UIImageView

UPDATE: Thanks to Ahmet AkkoK - for Swift (2.2) users blend mode macro has changed. CGBlendMode .kCGBlendModeNormal is replaced with CGBlendMode.Normal

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download