给uiview设置圆角

通常我们在给视图设置圆角时,都是通过UIViewCALayercornerRadius属性进行设置圆角,但改属性要么不设置要么四个角都是圆角。在某些需求中,我们需要某一给角或者某几个角是圆角,实现此方法可以重写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;
    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值