用UIRectCorner和 UIBezierPath 给UIView画圆角

我们如何设置UIView的圆角呢?
可以通过设置CALayer的cornerRadius属性:

view.layer.cornerRadius = 10;
用UIRectCorner和 UIBezierPath 给UIView画圆角_第1张图片
image.png

这样,就可以同时给四个角都设置圆角。

如果,我们只想给其中的某个角设置圆角的话,该怎么办?
我们可以通过UIBezierPath使用UIRectCorner画一个CAShapeLayer,然后赋值给UIView的layer的mask属性:

//Objective-C
view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    view.center = CGPointMake(self.view.frame.size.width/2, 200);
    view.backgroundColor = [UIColor brownColor];
    
    CGFloat cornerRadius = 10.0;
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(cornerRadius, cornerRadius)].CGPath;
    
    view.layer.mask = maskLayer;
    [self.view addSubview:view];
//swift
view = UIView.init(frame: .init(x: 0, y: 0, width: 200, height: 45))
        view.backgroundColor = UIColor.brown
        view.center = .init(x: self.view.frame.size.width/2, y: 230)
        self.view.addSubview(view)
        
        let cornerRadius = 8
        let maskLayer = CAShapeLayer()
        
        maskLayer.path = UIBezierPath.init(roundedRect: view.bounds, byRoundingCorners: [.bottomLeft,.bottomRight], cornerRadii: CGSize(width:cornerRadius,height:cornerRadius)).cgPath
        
        view.layer.mask = maskLayer
用UIRectCorner和 UIBezierPath 给UIView画圆角_第2张图片
image.png

demo地址:
swift
Objective-C

你可能感兴趣的:(用UIRectCorner和 UIBezierPath 给UIView画圆角)