我的应用程序主要是基于圆形和边框的。
我使用 UIView
的图层属性来设置圆角半径和边框。
但是我遇到了一个问题,角不清晰。
我得到以下结果:
UIButton
UIImageView
您可以在白色或灰色边框周围观察到一条细边框线。
这是我的代码:
button.layer.borderWidth = 2.0;
button.layer.borderColor = [[UIColor whiteColor] CGColor];
button.layer.cornerRadius = 4;
button.clipsToBounds = YES;
我已经搜索过解决这个问题,但没有成功。
我试过 button.layer.masksToBounds = YES
,但没有效果。
我错过了什么吗?还是有任何其他方法可以给我比 CALayer
更好的结果?
最佳答案
我尝试了很多解决方案,最后使用 UIBezierPath
。
我创建了 UIView
的类别并添加了制作圆形矩形和边框的方法。
这是该类别的方法:
- (void)giveBorderWithCornerRadious:(CGFloat)radius borderColor:(UIColor *)borderColor andBorderWidth:(CGFloat)borderWidth
{
CGRect rect = self.bounds;
//Make round
// Create the path for to make circle
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(radius, radius)];
// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = rect;
maskLayer.path = maskPath.CGPath;
// Set the newly created shape layer as the mask for the view's layer
self.layer.mask = maskLayer;
//Give Border
//Create path for border
UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:rect
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(radius, radius)];
// Create the shape layer and set its path
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.frame = rect;
borderLayer.path = borderPath.CGPath;
borderLayer.strokeColor = [UIColor whiteColor].CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.lineWidth = borderWidth;
//Add this layer to give border.
[[self layer] addSublayer:borderLayer];
}
我从这篇精彩的文章中得到了使用 UIBezierPath
的想法:Thinking like a Bézier path
我从这两个链接获得大部分代码:
- UIView category for rounding just the corners which you want, not all like CALayer cornerRadius.
- How to get a border on UIBezierPath
注意:这是类别方法,因此 self 代表调用此方法的 View 。如 UIButton、UIImageView 等
关于ios - 带边框的 cornerRadius : Glitch around border,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551053/