Based on an answer in here, I figured out a way to do this with these steps:
- Set the
UIView
background color to [UIColor clearColor]
- Manually draw a smaller circular background in
drawRect:
Here's the drawRect:
implementation:
- (void)drawRect:(CGRect)rect
{
CGFloat margin = _borderWidth;
CGRect background = CGRectMake(margin, margin,
self.bounds.size.width - 2 * margin,
self.bounds.size.height - 2 * margin);
CGContextRef context = UIGraphicsGetCurrentContext();
[_internalBackgroundColor set];
CGContextFillEllipseInRect(context, background);
}
And the overwritten backgroundColor
setter:
@property (nonatomic, strong) UIColor *internalBackgroundColor;
...
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
[super setBackgroundColor:[UIColor clearColor]];
_internalBackgroundColor = backgroundColor;
}
**** Faster solution: ****
As Kujey pointed out, it's better not to use the layer.cornerRadius
at all. Here's the drawRect:
solution without the layer
access:
- (void)drawRect:(CGRect)rect
{
CGFloat margin = _borderWidth / 2.0;
CGRect background = CGRectMake(margin, margin, self.bounds.size.width - 2 * margin, self.bounds.size.height - 2 * margin);
CGContextRef context = UIGraphicsGetCurrentContext();
[_internalBackgroundColor set];
CGContextFillEllipseInRect(context, background);
[_borderColor set];
CGContextSetLineWidth(context, _borderWidth);
CGContextStrokeEllipseInRect(context, background);
}