UIImage with transparent rounded corners

痴心易碎 提交于 2019-11-27 14:51:50

Here's a simpler formulation using UIKit calls:

- (UIImage*) roundCorneredImage: (UIImage*) orig radius:(CGFloat) r {
    UIGraphicsBeginImageContextWithOptions(orig.size, NO, 0);
    [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, orig.size} 
                                cornerRadius:r] addClip];
    [orig drawInRect:(CGRect){CGPointZero, orig.size}];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

Notice the NO parameter - this makes the image context transparent, so the clipped-out region is transparent.

https://github.com/detroit-labs/AmazeKit

sounds like a job for a library

Right after creating the bitmap context clear it with:

CGContextClearRect (context, CGRectMake(0, 0, w, h));

lukya's comment below your question is what you probably want to do.

Make sure you import QuartzCore:

#import <QuartzCore/QuartzCore.h>

Then, if you have a UIImageView of your image that you want to have rounded corners, just call (assuming imageView is a property and cornerRadius is the desired corner radius):

self.imageView.layer.cornerRadius = cornerRadius;
self.imageView.clipsToBounds = YES;

Since you already have self.CGImage, you could do this to create a UIImageView:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:self.CGImage]];

Just make sure to release the imageView after you add it as a subview.

profileImageView.layer.cornerRadius = profileImageView.frame.size.height/2;
profileImageView.clipsToBounds = YES;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!