If a add a border of a view using code in a view like
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = 2.0f;
the border is added inside the view like the following:
the right view is the original view, as you can see, the black area of bordered view is less than the original one. but what I want to get is a border outside of original view, like this:. the black area is equal to original one, how can I implement it?
Unfortunately, there isn't simply a little property you can set to align the border to the outside. It draws aligned to the inside because the UIViews default drawing operations draw within its bounds.
The simplest solution that comes to mind would be to expand the UIView by the size of the border width when applying the border:
Well there is no direct method to do it You can consider some workarounds.
If you dont need a definite border (clearcut border) then you can depend on shadow for the purpose
I liked solution of @picciano If you want exploding circle instead of square replace addExternalBorder function with:
Increase the width and height of view's frame with border width before adding the border:
Ok, there already is an accepted answer but I think there is a better way to do it, you just have to had a new layer a bit larger than your view and do not mask it to the bounds of the view's layer (which actually is the default behaviour). Here is the sample code :
Of course this is if you want your border to be 1 unity large, if you want more you adapt the
borderWidth
and the frame of the layer accordingly. This is better than using a second view a bit larger as aCALayer
is lighter than aUIView
and you don't have do modify the frame ofmyView
, which is good for instance ifmyView
is aUIImageView
N.B : For me the result was not perfect on simulator (the layer was not exactly at the right position so the layer was thicker on one side sometimes) but was exactly what is asked for on real device.
EDIT
Actually the problem I talk about in the N.B was just because I had reduced the screen of the simulator, on normal size there is absolutely no issue
Hope it helps
For a Swift implementation, you can add this as a UIView extension.