Add a circle around UIImage

For an app I worked on recently, we had the need to add a circle around an UIImage. When using a UIImageView, it is pretty straightforward to add a border to the image view. Unfortunately, we were using a library with no control over the UIImageView for a particular feature within the app and had to switch to manually adding the border in the UIImage before passing it over to the library. Here’s a category on UIImage to do so.

@implementation UIImage (PGHelpers)

- (UIImage *)borderedImageWithPadding:(int)padding {
    // Draw image
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width + padding, self.size.height + padding), NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawInRect:CGRectMake(padding / 2, padding / 2, self.size.width, self.size.height)];

    // Add border
    UIBezierPath *bezier = [UIBezierPath bezierPath];
    [bezier setLineWidth:4.f];
    [bezier setLineJoinStyle:kCGLineJoinRound];
    [bezier addArcWithCenter:CGPointMake(self.size.width / 2 + padding / 2, self.size.height / 2 + padding / 2) radius:self.size.height / 2 + padding / 2 - 2 startAngle:0 endAngle:M_PI clockwise:NO];
    [bezier addArcWithCenter:CGPointMake(self.size.width / 2 + padding / 2, self.size.height / 2 + padding / 2) radius:self.size.height / 2 + padding / 2 - 2 startAngle:M_PI endAngle:2 * M_PI clockwise:NO];
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    [bezier stroke];

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

@end
Published 24 Jan 2016

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter