Markus Rautopuro
Markus Rautopuro

Reputation: 8365

How to get rid of thin border in a UIView rounded with layer.cornerRadius in iOS 7.1.1?

I have a customized UIView that rounds its corners by using layer.cornerRadius like this:

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.layer.cornerRadius = self.frame.size.width / 2.0;
    self.layer.borderColor = [UIColor whiteColor].CGColor;
    self.layer.borderWidth = 2.0;
    self.layer.masksToBounds = YES;
    self.backgroundColor = [UIColor redColor];
}

How can I get rid of the very thin outer red circle?

Upvotes: 2

Views: 662

Answers (2)

Markus Rautopuro
Markus Rautopuro

Reputation: 8365

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);
}

Upvotes: 1

Kujey
Kujey

Reputation: 1122

Well, a more efficient way to do what you need would be to copy paste this function in the .m file of your custom view and call it in the drawRect method:

- (void)drawRoundedViewWithFrame: (CGRect)frame color:(UIColor *)color
{
    //// roundCircle Drawing
    UIBezierPath* roundCirclePath = [UIBezierPath bezierPathWithOvalInRect: frame];
    [color setFill];
    [roundCirclePath fill];
    [UIColor.whiteColor setStroke];
    roundCirclePath.lineWidth = 2;
    [roundCirclePath stroke];
}

Upvotes: 2

Related Questions