Reputation: 8599
currently I am rounding a UIImage using this code:
//round the image
UIImageView *roundView = [[UIImageView alloc] initWithImage:smallImage];
UIGraphicsBeginImageContextWithOptions(roundView.bounds.size, NO, [UIScreen mainScreen].scale);
[[UIBezierPath bezierPathWithRoundedRect:roundView.bounds
cornerRadius:roundView.frame.size.width/2] addClip];
[smallImage drawInRect:roundView.bounds];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
smallImage = finalImage;
//end round image
self.thumbnailView.image=smallImage;
UIImageWriteToSavedPhotosAlbum(smallImage, self, nil, nil); //20kb
UIGraphicsEndImageContext();
This however makes the outside of the circle white so when I press down on the image (if it's being used as a UIButton) you can see it's a square image. Is there anyway to clip a UIImage into a circle but make the outside of it transparent? Any pointers would be really appreciated.
Upvotes: 0
Views: 394
Reputation: 4725
I'm not quite sure why you have two calls to end the image context in your snippet, anyhow, although in theory the context itself should already be transparent (as you are passing NO to the opaque parameter), but in case it isn't, you can always fill it with transparent pixels before clipping and drawing the image
UIGraphicsBeginImageContextWithOptions(roundView.bounds.size, NO, 0.f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
CGContextFillRect(ctx, roundView.bounds);
[[UIBezierPath bezierPathWithRoundedRect:roundView.bounds
cornerRadius:roundView.frame.size.width/2] addClip];
[smallImage drawInRect:roundView.bounds];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I did try out both your code and the added fill code in a Swift playground and they seemed to produce similar results, so I am not convinced this will solve your issue, and it is possible that you have not shown us all of the code that could be manipulating the context.
PS! Passing 0 to the scale
automatically uses the correct main screen scale for the context ;)
EDIT: Just realised, your button probably has a white background set, which you usually wouldn't see under the image, but you do now as the image is transparent...
Upvotes: 0
Reputation: 1521
You can set the corner radius of UIImageView
to make it rounded like this:-
[yourImageView.layer setCornerRadius:CGRectGetWidth(yourImageView.frame)/2];
You can increase it to make it small.
Upvotes: 1