Making a UIImage to a circle form

Shahar Nechmad picture Shahar Nechmad · Sep 13, 2011 · Viewed 23.9k times · Source

I have been trying to mask a UIImage into a circle. I'm using now the code that has been popular on other answers here, but although I do get a circle its edges are very jagged and not smooth. Anyone can help? I do I get a perfect, smooth circle?

The code I'm using to create the mask is:

  (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef imageNoAlpha = image.CGImage;

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();

    CGFloat width = CGImageGetWidth(imageNoAlpha);
    CGFloat height = CGImageGetWidth(imageNoAlpha);

    CGContextRef ctxWithAlpha = CGBitmapContextCreate(nil, width, height, 8, 4*width, cs, kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(ctxWithAlpha, CGRectMake(0, 0, width, height), imageNoAlpha);

    CGImageRef imageWithAlpha = CGBitmapContextCreateImage(ctxWithAlpha);

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask);

    UIImage* retImage= [UIImage imageWithCGImage:masked];
    UIImage* retImageFixed = [retImage transparentBorderImage:1];

    CGImageRelease(mask);
    CGImageRelease(masked);
    CGImageRelease(imageWithAlpha);
    CGContextRelease(ctxWithAlpha);
    CGColorSpaceRelease(cs);

    return retImageFixed;

Thanks in advance...

Answer

Waseem Shah picture Waseem Shah · Feb 22, 2014

try this code

yourImageView.layer.cornerRadius = yourImageView.frame.size.height /2;
yourImageView.layer.masksToBounds = YES;
yourImageView.layer.borderWidth = 0;

this show image like ios 7 circle image thanks