Amrit Sidhu Amrit Sidhu - 6 months ago 67
Swift Question

Merge two images in swift

I am showing users on a map view with custom markers. Each marker will contain the user's image, like in the image below:enter image description here

There might be multiple users displayed as markers on the map. I get the data of users and their images through an API. The image which I receive from the API is just a rectangular image. But I have to show that image very similar to the above shown image. So I thought of two solution.


  1. Get the marker image from the API itself that can be easily displayed as an image on the map.

  2. I have the outer ellipse as an image. I can place a round image in that ellipse and create a new image. That can further be used as a marker. But for this I'll have to merge two photos. I am able to merge them. But the users image is always rectangle. I am not able to make it round.



Can any one help me with a better solution or just complete my solution?

Answer

The first option will be the easiest. If you re going with the second option then here's something:

-(UIImage *)makeRoundedImage:(UIImage *) image 
                  radius: (float) radius {

  CALayer *imageLayer = [CALayer layer];
  imageLayer.backgroundColor = [UIColor whiteColor].CGColor;
  imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
  imageLayer.contents = (id) image.CGImage;
  imageLayer.masksToBounds = YES;
  imageLayer.cornerRadius = radius;
  UIGraphicsBeginImageContext(image.size);
  [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return roundedImage;
}

This will create a round UIImage with a white background. Just use the resulting UIImage as the marker icon.

Comments