Skip to content

Instantly share code, notes, and snippets.

@rickytan
Created January 8, 2019 11:09
Show Gist options
  • Save rickytan/755a6a9dfc660e7a0909efb8e0197c5e to your computer and use it in GitHub Desktop.
Save rickytan/755a6a9dfc660e7a0909efb8e0197c5e to your computer and use it in GitHub Desktop.
UIImage Category
+ (UIImage *)rt_borderImageWithBorderColor:(UIColor *)borderColor fillColor:(UIColor *)fillColor borderWidth:(CGFloat)width radius:(CGFloat)radius forCorner:(UIRectCorner)corner
{
const CGFloat length = MAX(3, 2 * MAX(radius, width / 2) + width + 1.f / [UIScreen mainScreen].scale);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(length, length), NO, 0);
[borderColor ?: [UIColor clearColor] setStroke];
[fillColor ?: [UIColor clearColor] setFill];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(width / 2, width / 2, length - width, length - width)
byRoundingCorners:corner
cornerRadii:CGSizeMake(radius, radius)];
path.lineWidth = width;
if (radius >= 1.f / [UIScreen mainScreen].scale && (corner & UIRectCornerTopLeft) == UIRectCornerTopLeft) {
path.lineCapStyle = kCGLineCapRound;
}
else {
path.lineCapStyle = kCGLineCapSquare;
}
[path fill];
[path stroke];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
const CGFloat padding = MAX(MAX(radius, width / 2) + width / 2, 1);
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(padding, padding, padding, padding)
resizingMode:UIImageResizingModeStretch];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment