Skip to content

Instantly share code, notes, and snippets.

@radiovisual
Created March 11, 2015 11:42
Show Gist options
  • Save radiovisual/c202eff65fc83a850d73 to your computer and use it in GitHub Desktop.
Save radiovisual/c202eff65fc83a850d73 to your computer and use it in GitHub Desktop.
Make a perfect-circle cutout of any image in Objective-C
// This function will create perfect-circle cutout of any image you supply.
// So if you have a solid black image, the resulting PNG will be a "cutout-out" (transparent)
// circle with a border of solid black. It will return NSData (for use with Parse's PFFile),
// but can be easily modified to return the resulting UIImage (*img)
//
// @param {UIImage} The image you want to "cutout"
// @param {CGSize} The size (width and height) you want the resulting image to be
// return {NSData} the PNGrepresentation of the resulting UIImage
-(NSData *)createCircleCutOutofImage:(UIImage *)image withSize:(CGSize)size {
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
CGRect clippingEllipseRect = CGRectMake(0, 0, size.width, size.width);
CGContextAddEllipseInRect(context, clippingEllipseRect);
CGContextClip(context);
CGContextClearRect(context, clippingEllipseRect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// return NSData
return UIImagePNGRepresentation(img);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment