[英]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: 我有一个自定义的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];
}
How can I get rid of the very thin outer red circle? 如何摆脱非常细的外部红色圆圈?
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: 好吧,一种更有效的方法来执行所需的操作是将此函数复制粘贴到自定义视图的.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];
}
Based on an answer in here , I figured out a way to do this with these steps: 根据此处的答案,我找到了一种通过以下步骤实现此目的的方法:
UIView
background color to [UIColor clearColor]
UIView
背景颜色设置为[UIColor clearColor]
drawRect:
drawRect:
手动绘制较小的圆形背景drawRect:
Here's the drawRect:
implementation: 这是
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);
}
And the overwritten backgroundColor
setter: 以及覆盖的
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. 正如Kujey指出的,最好不要使用
layer.cornerRadius
。 Here's the drawRect:
solution without the layer
access: 这是
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.