You need to create a new context and then draw the image again:
UIImage *image = yourImage; UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); [image drawAtPoint:CGPointZero]; [[UIColor whiteColor] setStroke]; UIRectFrame(CGRectMake(0, 0, image.size.width, image.size.height)); UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
UIRectFrame
draws a UIRectFrame
border. If you need more, you need to use UIBezierPath
instead.
UIImage *image = yourImage; UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); [image drawAtPoint:CGPointZero]; [[UIColor whiteColor] setStroke]; UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, image.size.width, image.size.height)]; path.lineWidth = 2.0; [path stroke]; UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
For full implementation as a category on UIImage
:
UIImage + Bordered.h
@interface UIImage (Bordered) -(UIImage *)imageBorderedWithColor:(UIColor *)color borderWidth:(CGFloat)width; @end
UIImage + Bordered.m
@implementation UIImage (Bordered) -(UIImage *)imageBorderedWithColor:(UIColor *)color borderWidth:(CGFloat)width { UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); [self drawAtPoint:CGPointZero]; [color setStroke]; UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, self.size.width, self.size.height)]; path.lineWidth = width; [path stroke]; UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return result; } @end
Then using it is as simple as:
UIImage *image = yourImage; UIImage *borderedImage = [image imageBorderedWithColor:[UIColor whiteColor] borderWidth:2.0];
source share