如何摆脱iOS 7.1.1中使用layer.cornerRadius舍入的UIView中的细边框?

时间:2014-05-27 13:40:10

标签: ios uiview

我有一个自定义的UIView,通过像这样使用layer.cornerRadius来转弯:

- (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];
}

如何摆脱非常薄的外部红圈?

2 个答案:

答案 0 :(得分:2)

那么,一种更有效的方法来做你需要的就是将这个函数复制粘贴到自定义视图的.m文件中并在drawRect方法中调用它:

- (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];
}

答案 1 :(得分:1)

根据here中的答案,我找到了通过以下步骤完成此操作的方法:

  • UIView背景颜色设置为[UIColor clearColor]
  • drawRect:
  • 中手动绘制较小的圆形背景

以下是drawRect:实施:

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

被覆盖的backgroundColor二传手:

@property (nonatomic, strong) UIColor *internalBackgroundColor;

...

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:[UIColor clearColor]];

    _internalBackgroundColor = backgroundColor;
}

****更快的解决方案:****

正如Kujey所指出的,最好不要使用layer.cornerRadius。以下是没有drawRect:访问权限的layer解决方案:

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