Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CGContextClip to clip a circle with image

Have a imageViewA (frame{0,0,320,200}) in my app, and I want to clip a circle with the imageViewA's center, radius=50, and draw into another imageViewB (frame{0,0,100,100}); the original image effect like this :

enter image description here

and use below code to clip:

UIGraphicsBeginImageContext(self.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat height = self.bounds.size.height;
CGContextTranslateCTM(ctx, 0.0, height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, 50, 0, 2*M_PI, 0);
CGContextClosePath(ctx);
CGContextSaveGState(ctx);
CGContextClip(ctx);
CGContextDrawImage(ctx, CGRectMake(0,0,self.frame.size.width, self.frame.size.height), image.CGImage);
CGContextRestoreGState(ctx);
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
NSString *headerPath = [NSString stringWithFormat:@"%@/header.png",HomeDirectory];
NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
if([imageData writeToFile:headerPath atomically:YES]){
    imageViewB.image = [UIImage imageWithContentsOfFile:headerPath];
}

clip image effect like this:

enter image description here

I only need the circle view, but the clip effect display that imageViewB has white space. How to clip this image correctly? Thanks!

like image 961
Roby Avatar asked Nov 22 '25 11:11

Roby


2 Answers

imageViewB.layer.cornerRadius = 50.0;
imageViewB.layer.masksToBounds = YES;
like image 91
Hafthor Avatar answered Nov 24 '25 00:11

Hafthor


JPEG doesn't support transparency. Use UIImagePNGRepresentation instead of UIImageJPEGRepresentation, and you will have the result you want.

NSData *imageData = UIImagePNGRepresentation(newImage);
if([imageData writeToFile:headerPath atomically:YES]){
    imageViewB.image = [UIImage imageWithContentsOfFile:headerPath];
}
like image 36
Emmanuel Avatar answered Nov 24 '25 01:11

Emmanuel