How can I set the border of a UIImage
?
-
By chance if anyone lands hear by a google search (as I did) and are looking for adding a border to UIImageView, look for the answer by @mclin at bottom. Works great! – Mahendra Liya Mar 25 '15 at 07:53
16 Answers
With OS > 3.0 you can do this:
//you need this import
#import <QuartzCore/QuartzCore.h>
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];

- 3,599
- 1
- 20
- 18
-
1When i aspectFit the images in the above imageView, the image is viewed perfectly but the sides of image is left blank, and the same happens to the upper and lower portion of the image when image is landscape. The blank space looks ugly with border set to it.. Did you faced this issue? If yes, please suggest a method to solve this – Meet Jun 12 '12 at 08:24
-
-
6Yes you can. Instances of `UIImage` can be drawn into a graphics context with CoreGraphics. – Mark Adams Jun 02 '13 at 01:56
-
As @rockstar points out, you may need to add imageView.layer.masksToBounds = YES; – Bjorn Roche Apr 30 '14 at 15:44
-
This [link](http://eureka.ykyuen.info/2010/08/27/iphone-uiview-with-border/) was the solution I was looking for. – GrandSteph Jul 21 '14 at 18:39
-
I think it's important to note that the CALayer border is drawn over the layer contents without affecting the layer's content area, so when applied to a UIImageView for example, the border is drawn over the 4 edges of the image (if the contentMode is such that the image fills the view). If you need the image to be completely visible, and not mess with contentModes and making resized UIImage, then I think nested views/layers is the only option. – androidguy Sep 15 '20 at 07:24
You can do this by creating a new image (also answered in your other posting of this question):
- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
CGSize size = [source size];
UIGraphicsBeginImageContext(size);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
[source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
CGContextStrokeRect(context, rect);
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
This code will produce a pink border around the image. However if you are going to just display the border then use the layer of the UIImageView
and set its border.

- 46,571
- 9
- 101
- 182
-
-
@MarcusS.Zarra I realise they didn't exist when this question was answered, but this solution doesn't take the Retina display into consideration. If you could revise it I'd be really grateful :) – Luke Apr 05 '13 at 17:11
-
@lukech The sample doesn't need to be revised. Just increase the line width if you are on a retina device. – Marcus S. Zarra Apr 05 '13 at 18:11
-
2The `size` is 320x480 regardless of whether or not you're on a Retina device, so when you save the image, it saves at that 320x480px resolution, not 640x960. – Luke Apr 05 '13 at 19:07
-
Working on it right now, but how can I round the corners of this border? – SirRupertIII Mar 04 '14 at 17:48
-
@KKendall I would suggest creating your own stack overflow question and reference this one. – Marcus S. Zarra Mar 04 '14 at 18:10
#import <QuartzCore/CALayer.h>
UIImageView *imageView = [UIImageView alloc]init];
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor = [UIColor blackColor].CGColor;
imageView.layer.borderWidth = 1;
This code can be used for adding UIImageView
view border.

- 1,986
- 1
- 19
- 30

- 833
- 10
- 13
-
perfect! No need to go through the hassle of CGImage. (I didn't need to save the image with the border). Thanks a bunch! – Septronic Jan 05 '16 at 03:13
imageView_ProfileImage.layer.cornerRadius =10.0f;
imageView_ProfileImage.layer.borderColor = [[UIColor blackColor] CGColor];
imageView_ProfileImage.layer.borderWidth =.4f;
imageView_ProfileImage.layer.masksToBounds = YES;

- 3,118
- 7
- 26
- 34

- 617
- 6
- 4
-
Brilliant hack, especially when it comes to memory usage - the other answers will take 2x memory just to add that border momentarily. Pro tip - If you're looking to just add a border on one side, then you can change the bounds too. Great answer! – judepereira Jul 21 '17 at 09:54
If you know the dimensions of your image, then adding a border to the UIImageView's layer is the best solution AFAIK. Infact, you can simply setFrame your imageView to x,y,image.size.width,image.size.height
In case you have an ImageView of a fixed size with dynamically loaded images which are getting resized (or scaled to AspectFit), then your aim is to resize the imageview to the new resized image.
The shortest way to do this:
// containerView is my UIImageView
containerView.layer.borderWidth = 7;
containerView.layer.borderColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0].CGColor;
// this is the key command
[containerView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, containerView.frame)];
But to use the AVMakeRectWithAspectRatioInsideRect, you need to add this
#import <AVFoundation/AVFoundation.h>
import statement to your file and also include the AVFoundation framework in your project (comes bundled with the SDK).

- 2,491
- 1
- 18
- 18
You can't add a border, but this would work for the same effect. You could also make the UIView called blackBG in this example into a UIImageView with a border image and a blank middle, and then you'd have a custom image border instead of just black.
UIView *blackBG = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
blackBG.backgroundColor = [UIColor blackColor];
UIImageView *myPicture = [[UIImageView alloc] initWithImage:
[UIImage imageNamed: @"myPicture.jpg"]];
int borderWidth = 10;
myPicture.frame = CGRectMake(borderWidth,
borderWidth,
blackBG.frame.size.width-borderWidth*2,
blackBG.frame.size.height-borderWidth*2)];
[blackBG addSubview: myPicture];

- 13,108
- 13
- 75
- 116
-
This is what I ended up doing; nesting my `UIImageView` in the center of a slightly-larger `UIView` of my frame color. – Ben Kreeger Nov 07 '12 at 19:25
all these answers work fine BUT add a rect to an image. Suppose You have a shape (in my case a butterfly) and You want to add a border (a red border):
we need two steps: 1) take the image, convert to CGImage, pass to a function to draw offscreen in a context using CoreGraphics, and give back a new CGImage
2) convert to uiimage back and draw:
// remember to release object!
+ (CGImageRef)createResizedCGImage:(CGImageRef)image toWidth:(int)width
andHeight:(int)height
{
// create context, keeping original image properties
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width,
height,
8
4 * width,
colorspace,
kCGImageAlphaPremultipliedFirst
);
CGColorSpaceRelease(colorspace);
if(context == NULL)
return nil;
// draw image to context (resizing it)
CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
CGSize offset = CGSizeMake(2,2);
CGFloat blur = 4;
CGColorRef color = [UIColor redColor].CGColor;
CGContextSetShadowWithColor ( context, offset, blur, color);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imgRef;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect frame = CGRectMake(0,0,160, 122);
UIImage * img = [UIImage imageNamed:@"butterfly"]; // take low res OR high res, but frame should be the low-res one.
imgV = [[UIImageView alloc]initWithFrame:frame];
[imgV setImage: img];
imgV.center = self.view.center;
[self.view addSubview: imgV];
frame.size.width = frame.size.width * 1.3;
frame.size.height = frame.size.height* 1.3;
CGImageRef cgImage =[ViewController createResizedCGImage:[img CGImage] toWidth:frame.size.width andHeight: frame.size.height ];
imgV2 = [[UIImageView alloc]initWithFrame:frame];
[imgV2 setImage: [UIImage imageWithCGImage:cgImage] ];
// release:
if (cgImage) CGImageRelease(cgImage);
[self.view addSubview: imgV2];
}
I added a normal butterfly and a red-bordered bigger butterfly.

- 10,876
- 3
- 61
- 48
You can add border to the UIImageView, and then change the size of the UIimageView according to the image size:
#import <QuartzCore/QuartzCore.h>
// adding border to the imageView
[imageView.layer setBorderColor: [[UIColor whiteColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
// resize the imageView to fit the image size
CGSize size = [image size];
float factor = size.width / self.frame.size.width;
if (factor < size.height / self.frame.size.height) {
factor = size.height / self.frame.size.height;
}
CGRect rect = CGRectMake(0, 0, size.width/factor, size.height/factor);
imageView.frame = rect;
Make sure you to set the origin of the imageView to the center

- 71
- 1
- 3
You could manipulate the image itself, but a much better way is to simply add a UIView that contains the UIImageView, and change the background to black. Then set the size of that container view to a little bit larger than the UIImageView.

- 74,769
- 26
- 128
- 150
-
Is it going to work with a different size of images that change on the fly? The UIImageView will change all the time, and the UIView? p.s. Manipulate the image itself will be great. – Shay Aug 31 '09 at 06:38
-
You'd have to adjust the frame of the containing view along with the image - you could save off the center properties for both views, adjust the image size, adjust the container size, and then re-set center properties for both. – Kendall Helmstetter Gelner Aug 31 '09 at 20:04
-
This is exactly the way I did it as opposed to stroking the path with CG. just seemed easier. – Corey Floyd Aug 31 '09 at 22:04
Another way is to do directly from designer.
Select your image and go under "Show the Identity inspector".
Here you can manually add "User Defined Runtime Attributes":
layer.borderColor
layer.borderWidth

- 21,000
- 15
- 120
- 146
-
1This is not going to work as you need CGColor and through XIB it provides only UIColor – codesnooker May 30 '15 at 12:06
-
Color won't work, but if you just need a black one - this is the most "lines of code" efficient answer =D – soprof Jul 27 '15 at 10:48
This function will return you image with black border try this.. hope this will help you
- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
CGSize size = CGSizeMake(image.size.width,image.size.height);
UIGraphicsBeginImageContext(size);
CGPoint thumbPoint = CGPointMake(0,0);
[image drawAtPoint:thumbPoint];
UIGraphicsBeginImageContext(size);
CGImageRef imgRef = blackBorderImage.CGImage;
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPoint starredPoint = CGPointMake(0, 0);
[imageCopy drawAtPoint:starredPoint];
UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageC;
}

- 1,493
- 1
- 12
- 21

- 6,401
- 3
- 33
- 39
-
If you found any gliches please let me know... i will improve it – SachinVsSachin Jan 12 '13 at 09:08
//you need to import
QuartzCore/QuartzCore.h
& then for ImageView in border
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
[imageView.layer setCornerRadius: 5.0];

- 82,064
- 23
- 174
- 143

- 169
- 1
- 9
In Swift 3 here's how you do it to the UIImage itself:
let size = CGSize(width: image.size.width, height: image.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image?.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.imageView.image = newImage

- 646
- 1
- 8
- 19
For those looking for a plug-and-play solution on UIImage, I wrote CodyMace's answer as an extension.
Usage: let outlined = UIImage(named: "something")?.outline()
extension UIImage {
func outline() -> UIImage? {
let size = CGSize(width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
self.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}

- 2,050
- 2
- 18
- 17
I have created a class which adds a border to imageView h. Use this class instead of UIImageView.I have given a padding of 4. You can give as per your wish.
class UIBorderImageView: UIView {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.White()
self.layer.borderColor = UIColor.GreyMedium().cgColor
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 4.0
self.layer.masksToBounds = true
self.setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUpViews(){
self.addSubview(imageView)
self.addConstraintsWithFormat(format: "H:|-4-[v0]-4-|", views: imageView)
self.addConstraintsWithFormat(format: "V:|-4-[v0]-4-|", views: imageView)
}
func configureImageViewWith(image:UIImage){
self.imageview.image = image
}}

- 741
- 9
- 10
I use this method to add a border outside the image. You can customise the border width in boderWidth
constant.
Swift 3
func addBorderToImage(image : UIImage) -> UIImage {
let bgImage = image.cgImage
let initialWidth = (bgImage?.width)!
let initialHeight = (bgImage?.height)!
let borderWidth = Int(Double(initialWidth) * 0.10);
let width = initialWidth + borderWidth * 2
let height = initialHeight + borderWidth * 2
let data = malloc(width * height * 4)
let context = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: (bgImage?.colorSpace)!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue);
context?.draw(bgImage!, in: CGRect(x: CGFloat(borderWidth), y: CGFloat(borderWidth), width: CGFloat(initialWidth), height: CGFloat(initialHeight)))
context?.setStrokeColor(UIColor.white.cgColor)
context?.setLineWidth(CGFloat(borderWidth))
context?.move(to: CGPoint(x: 0, y: 0))
context?.addLine(to: CGPoint(x: 0, y: height))
context?.addLine(to: CGPoint(x: width, y: height))
context?.addLine(to: CGPoint(x: width, y: 0))
context?.addLine(to: CGPoint(x: 0, y: 0))
context?.strokePath()
let cgImage = context?.makeImage()
let uiImage = UIImage(cgImage: cgImage!)
free(data)
return uiImage;
}

- 1,379
- 14
- 25