iOS UIView 单独设置一个角为圆角,两个 三个角也行
效果图:
如下所示调用方法两句话 很简单:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 100)]; label.backgroundColor = [UIColor blueColor]; [self.view addSubview:label]; UIRectCorner corners = UIRectCornerTopRight | UIRectCornerBottomRight; [label setBorderWithCornerRadius:50 borderWidth:10 borderColor:[UIColor redColor] type:corners]; }
UIView 类别里面的实现:
@implementation UIView (lcAnyCorners) - (void)setBorderWithCornerRadius:(CGFloat)cornerRadius borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor type:(UIRectCorner)corners { // UIRectCorner type = UIRectCornerTopRight | UIRectCornerBottomRight | UIRectCornerBottomLeft; //1. 加一个layer 显示形状 CGRect rect = CGRectMake(borderWidth/2.0, borderWidth/2.0, CGRectGetWidth(self.frame)-borderWidth, CGRectGetHeight(self.frame)-borderWidth); CGSize radii = CGSizeMake(cornerRadius, borderWidth); //create path UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:radii]; //create shape layer CAShapeLayer *shapeLayer = [CAShapeLayer layer]; shapeLayer.strokeColor = borderColor.CGColor; shapeLayer.fillColor = [UIColor clearColor].CGColor; shapeLayer.lineWidth = borderWidth; shapeLayer.lineJoin = kCALineJoinRound; shapeLayer.lineCap = kCALineCapRound; shapeLayer.path = path.CGPath; [self.layer addSublayer:shapeLayer]; //2. 加一个layer 按形状 把外面的减去 CGRect clipRect = CGRectMake(0, 0, CGRectGetWidth(self.frame)-1, CGRectGetHeight(self.frame)-1); CGSize clipRadii = CGSizeMake(cornerRadius, borderWidth); UIBezierPath *clipPath = [UIBezierPath bezierPathWithRoundedRect:clipRect byRoundingCorners:corners cornerRadii:clipRadii]; CAShapeLayer *clipLayer = [CAShapeLayer layer]; clipLayer.strokeColor = borderColor.CGColor; shapeLayer.fillColor = [UIColor clearColor].CGColor; clipLayer.lineWidth = 1; clipLayer.lineJoin = kCALineJoinRound; clipLayer.lineCap = kCALineCapRound; clipLayer.path = clipPath.CGPath; self.layer.mask = clipLayer; } @end
github 地址: https://github.com/lc081200/AnyCornersExample