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...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…