Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 951
Alex Stone Avatar asked Mar 06 '12 14:03

Alex Stone


2 Answers

I have never done anything like that, but try using QuartzCore framework and its' cornerRadius property. Example:

#import <QuartzCore/QuartzCore.h>
//some other code ...
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
imgView.layer.cornerRadius = 10.0f;

play around with it a bit and you will get what you want.

Hope it helps

like image 96
Novarg Avatar answered Oct 16 '22 11:10

Novarg


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;
}
like image 34
calimarkus Avatar answered Oct 16 '22 09:10

calimarkus