Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@interface UIView (AddCorner)
/**
Add Corner without border.
@discussion It only support to add corner without border.
If with border, use `addCorner:borderWidth:borderColor:`
*/
- (void)addCorner:(CGFloat)radius;
/**
Add Corner with border.
@discussion Can't use the system border after use it to show a border.
*/
- (void)addCorner:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor*)borderColor;
@end
@implementation UIView (AddCorner)
- (void)addCorner:(CGFloat)radius {
UIImageView * imageView = [[UIImageView alloc] initWithImage:[self drawRoundedCorner:radius
borderWidth:0
borderColor:nil]];
[self insertSubview:imageView atIndex:0];
self.backgroundColor = [UIColor clearColor];
}
- (void)addCorner:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor {
UIImageView * imageView = [[UIImageView alloc] initWithImage:[self drawRoundedCorner:radius
borderWidth:borderWidth
borderColor:borderColor]];
[self insertSubview:imageView atIndex:0];
self.backgroundColor = [UIColor clearColor];
}
- (UIImage *)drawRoundedCorner:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, [UIScreen mainScreen].scale);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, borderWidth);
CGContextSetStrokeColorWithColor(context, borderColor.CGColor ?: self.backgroundColor.CGColor);
CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor ?: [UIColor clearColor].CGColor);
CGFloat width = self.bounds.size.width;
CGFloat height = self.bounds.size.height;
// From Right-Top point
CGContextMoveToPoint(context, width, radius);
// Go to Right-Bottom point
CGContextAddArcToPoint(context, width, height, width - radius, height, radius);
// Go to Left-Bottom point
CGContextAddArcToPoint(context, 0, height, 0, height - radius, radius);
// Go to Left-Top point
CGContextAddArcToPoint(context, 0, 0, width, 0, radius);
// Go to RIght-Top Point
CGContextAddArcToPoint(context, width, 0, width, radius, radius);
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
UIImage * contentImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return contentImg;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.