How to set cornerRadius for only top-left and top-right corner of a UIView?

后端 未结 26 3293
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:14

Is there a way to set cornerRadius for only top-left and top-right corner of a UIView?

I tried the following, but it end up not seeing the

26条回答
  •  没有蜡笔的小新
    2020-11-22 06:59

    I am not sure why your solution did not work but the following code is working for me. Create a bezier mask and apply it to your view. In my code below I was rounding the bottom corners of the _backgroundView with a radius of 3 pixels. self is a custom UITableViewCell:

    UIBezierPath *maskPath = [UIBezierPath
        bezierPathWithRoundedRect:self.backgroundImageView.bounds
        byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
        cornerRadii:CGSizeMake(20, 20)
    ];
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    
    self.backgroundImageView.layer.mask = maskLayer;
    

    Swift version with some improvements:

    let path = UIBezierPath(roundedRect:viewToRound.bounds, byRoundingCorners:[.TopRight, .BottomLeft], cornerRadii: CGSizeMake(20, 20))
    let maskLayer = CAShapeLayer()
    
    maskLayer.path = path.CGPath
    viewToRound.layer.mask = maskLayer
    

    Swift 3.0 version:

    let path = UIBezierPath(roundedRect:viewToRound.bounds,
                            byRoundingCorners:[.topRight, .bottomLeft],
                            cornerRadii: CGSize(width: 20, height:  20))
    
    let maskLayer = CAShapeLayer()
    
    maskLayer.path = path.cgPath
    viewToRound.layer.mask = maskLayer
    

    Swift extension here

提交回复
热议问题