Girish
Girish

Reputation: 4712

Set border around UIImageView

I want to apply two types of border on a UIImageView:

  1. One is the border on the layer of the UIImageView.
  2. Second is the border around the layer of the UIImageView.

How can I do this?

Upvotes: 17

Views: 28369

Answers (4)

iOS Blacksmith
iOS Blacksmith

Reputation: 141

Swift 5

Beware when using a UIImageView; masksToBounds = false means the image will spill over

let outsideBorder = CALayer()
outsideBorder.frame = CGRect(x: -1, y: -1, width: myView.frame.size.width+2, height: myView.frame.size.height+2)
outsideBorder.borderColor = UIColor.black.cgColor
outsideBorder.borderWidth = 1.0

myView.layer.addSublayer(outsideBorder)
myView.masksToBounds = false

Upvotes: 0

Jonathan King
Jonathan King

Reputation: 1528

Try

#define kBorderWidth 3.0
#define kCornerRadius 8.0
CALayer *borderLayer = [CALayer layer];
CGRect borderFrame = CGRectMake(0, 0, (imageView.frame.size.width), (imageView.frame.size.height));
[borderLayer setBackgroundColor:[[UIColor clearColor] CGColor]];
[borderLayer setFrame:borderFrame];
[borderLayer setCornerRadius:kCornerRadius];
[borderLayer setBorderWidth:kBorderWidth];
[borderLayer setBorderColor:[[UIColor redColor] CGColor]];
[imageView.layer addSublayer:borderLayer];

And don't forget to import QuartzCore/QuartzCore.h

This example will draw a boarder on the layer, but change it's frame slightly to make the border around the layer.

Upvotes: 32

Hugues Duvillier
Hugues Duvillier

Reputation: 487

An other way is to add another layer that goes a bit outside of the UIImageView's layer like so :

CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;

[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;

Upvotes: 2

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

Another way

You must import

#import <QuartzCore/QuartzCore.h>

Then add code for your UIImageView

imgView.clipsToBounds = YES;
imgView.layer.cornerRadius = 8.0;
imgView.layer.borderWidth = 2.0;
imgView.layer.borderColor = [UIColor greenColor].CGColor;

Upvotes: 9

Related Questions