通常我们在给视图设置圆角时,都是通过UIView
的CALayer
的cornerRadius
属性进行设置圆角,但改属性要么不设置要么四个角都是圆角。在某些需求中,我们需要某一给角或者某几个角是圆角,实现此方法可以重写uiview的drawRect方法自己重绘。还有一种方式;UIBezierPath有自动绘制圆角矩形的构造方法,通过使用CAShapeLayer
来实现,下面通过CAShapeLayer
实现圆角。
-(void)setBorderWithCorner:(UIView *)view Radius:(CGFloat)cornerRadius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor
type:(UIRectCorner)corners
{
CGSize size = view.bounds.size;
CGRect rect = CGRectMake(borderWidth*0.5, borderWidth*0.5, size.width - borderWidth, size.height - borderWidth);
CGSize cornerSize = CGSizeMake(cornerRadius, borderWidth);
UIBezierPath *cornerPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:cornerSize];
CAShapeLayer *radiuShape = [CAShapeLayer layer];
radiuShape.fillColor = [UIColor clearColor].CGColor;
radiuShape.lineWidth = borderWidth;
if (borderColor) {
radiuShape.strokeColor = borderColor.CGColor;
}
radiuShape.path =cornerPath.CGPath;
[view.layer addSublayer:radiuShape];
CGRect maskRect = CGRectMake(0, 0, CGRectGetWidth(view.frame), CGRectGetHeight(view.frame));
CGSize clipRadii = CGSizeMake(cornerRadius, borderWidth);
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:maskRect byRoundingCorners:corners cornerRadii:clipRadii];
CAShapeLayer *maskShape = [CAShapeLayer layer];
maskShape.strokeColor = borderColor.CGColor;
radiuShape.fillColor = [UIColor clearColor].CGColor;
maskShape.lineWidth = 1;
maskShape.path = maskPath.CGPath;
view.layer.mask = maskShape;
}