Alex Stone Alex Stone - 1 year ago 130
iOS Question

iPhone programmatically crop a square image to appear as circle

I'm trying to create an image for a custom style UIButton using an image from the camera roll on iPhone. The button has a circular background and effectively appears as a circle. Now I need an image to go in the middle of the button that also appears round.

How do I cut a square UIImage to appear round with transparency outside of the round area?

If masking is involved, do I need to pre-render a mask or can I create one programmatically(ex: a circle)?

Thank you!

Answer Source

Yes you can use CoreGraphics to draw the mask dynamically. Then you can create the masked image.

Example for masking:

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage
  CGImageRef maskRef = maskImage.CGImage;
  CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                      CGImageGetDataProvider(maskRef), NULL, false);

  CGImageRef maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
  UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
  return maskedImage;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download