iPhone programmatically crop a square image to appear as circle

Alex Stone picture Alex Stone · Mar 6, 2012 · Viewed 23k times · Source

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

Novarg picture Novarg · Mar 6, 2012

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