View的任意圆角和边框

1.如果需要将UIView的4个角全部都为圆角,添加边框,做法相当简单,只需设置其Layer的cornerRadius、borderWidth、borderColor就可以了。

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.layer.cornerRadius = 25;
    view.layer.borderWidth = 1;
    view.layer.borderColor = [UIColor redColor].CGColor;
    [self.view addSubview:view];
圆角边框.png

2.如果要指定某几个角为圆角而别的不变时,最简单优雅的方案,就是使用UIBezierPath。

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor lightGrayColor];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomLeft cornerRadii:CGSizeMake(25, 25)];
    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.path = path.CGPath;
    view.layer.mask = mask;
任意圆角.png

其中,参数:(UIRectCorner)corners指定了需要成为圆角的角,使用“|”来组合。

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,
    UIRectCornerTopRight    = 1 << 1,
    UIRectCornerBottomLeft  = 1 << 2,
    UIRectCornerBottomRight = 1 << 3,
    UIRectCornerAllCorners  = ~0UL
};

3.给上面切了两个圆角的view增加边框。
如果直接设置borderWidth和borderColor,设置圆角的部分边线被贝塞尔曲线切掉。


圆角边线被切掉.png

解决思路:用UIBezierPath画好边框,在切圆角。
给view加了一个Category

- (void)applyRoundCorners:(UIRectCorner)corners radius:(CGFloat)radius
{
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    
    CAShapeLayer *temp = [CAShapeLayer layer];
    temp.lineWidth = 2.f;
    temp.fillColor = [UIColor clearColor].CGColor;
    temp.strokeColor = [UIColor redColor].CGColor;
    temp.frame = self.bounds;
    temp.path = path.CGPath;
    [self.layer addSublayer:temp];
    
    CAShapeLayer *mask = [[CAShapeLayer alloc]initWithLayer:temp];
    mask.path = path.CGPath;
    self.layer.mask = mask;
}

使用示例:

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:view];
    [view applyRoundCorners:UIRectCornerTopRight|UIRectCornerBottomLeft radius:25];
最终效果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容