Search code examples
iphoneobjective-ciosuiimagecrop

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!


Solution

  • 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),
                                          CGImageGetHeight(maskRef),
                                          CGImageGetBitsPerComponent(maskRef),
                                          CGImageGetBitsPerPixel(maskRef),
                                          CGImageGetBytesPerRow(maskRef),
                                          CGImageGetDataProvider(maskRef), NULL, false);
    
      CGImageRef maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
      UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
      CGImageRelease(maskedImageRef);
      CGImageRelease(mask);
      return maskedImage;
    }