12

i have 2 images: first one is the user personal image, the second one is an icon (badge).

i want to add the second uiimage (icon) on the bottom left corner of the first uiimage (user's image) and save them into a new Uiimage.

thanks

Richard Stelling
  • 25,607
  • 27
  • 108
  • 188
Kassem
  • 1,481
  • 3
  • 20
  • 42

2 Answers2

28

Try this method:

-(UIImage *)drawImage:(UIImage*)profileImage withBadge:(UIImage *)badge
{
    UIGraphicsBeginImageContextWithOptions(profileImage.size, NO, 0.0f);
    [profileImage drawInRect:CGRectMake(0, 0, profileImage.size.width, profileImage.size.height)];
    [badge drawInRect:CGRectMake(0, profileImage.size.height - badge.size.height, badge.size.width, badge.size.height)];
     UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return resultImage;
}

You can use it by:

UIImage *myBadgedImage = [self drawImage:profileImage withBadge:badgeImage];
graver
  • 15,183
  • 4
  • 46
  • 62
  • Any idea why the code would take certain UIImages and just zoom in on them - essentially losing the actual size? This code is not working for us as our images are getting zoomed in on - even if we only pass the profile image without a badge. – Praxiteles Jun 12 '15 at 11:22
  • saved my day. I wish I did not have to revert to this an have UIImageViews stacked on top of one another instead of using this helper though – Anton Tropashko Mar 17 '16 at 12:10
  • @AntonTropashko badge.size.height varies on different image i.e badge image resizing. can we make it as fit (say 100 height) in any profileImage size? Thanks! – Gopik Mar 19 '18 at 10:37
2

Try this:

CGFloat scale = [self currentScale];
if (scale > 1.5)
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, scale);
else
    UIGraphicsBeginImageContext(view.frame.size);

[image1 drawInRect:CGRectMake(0, 0, w1, h1)];
[image2 drawInRect:CGRectMake(0, 0, w2, h2)];

UIImage* screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
sergio
  • 68,819
  • 11
  • 102
  • 123