如何摆脱iOS 7.1.1中的layer.cornerRadius四舍五入的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]; } 

我怎样才能摆脱非常薄的外部红色圆圈?

那么,一个更有效的方法来做你所需要的就是把这个函数粘贴到你的自定义视图的.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]; } 

根据这里的答案,我想出了一个方法来完成这些步骤:

  • UIView背景颜色设置为[UIColor clearColor]
  • drawRect:手动绘制一个较小的圆形背景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 setter:

 @property (nonatomic, strong) UIColor *internalBackgroundColor; ... - (void)setBackgroundColor:(UIColor *)backgroundColor { [super setBackgroundColor:[UIColor clearColor]]; _internalBackgroundColor = backgroundColor; } 

****更快的解决scheme:****

正如Kujey指出的,最好不要使用layer.cornerRadius 。 这里是没有layer访问的drawRect:解决scheme:

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