如何为UIView的左上角和右上角设置cornerRadius?

548

有没有一种方法可以仅为UIView的左上角和右上角设置cornerRadius

我尝试了以下方法,但最终导致无法看到视图。

UIView *view = [[UIView alloc] initWithFrame:frame];

CALayer *layer = [CALayer layer];
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
layer.shadowPath = shadowPath.CGPath;
view.layer.mask = layer;

9
在您的编辑后,有三个需要修正的地方:(1)圆角路径应基于 view.bounds,而不是 frame;(2)图层应该是一个 CAShapeLayer,而不是 CALayer;(3)设置图层的 path,而不是 shadowPath - Kurt Revis
1
可能是这个问题的重复:question & answer - Stuart
使用Bezier曲线算法,在CGPath上创建曲线。我相信它是CoreGraphics的一部分。如果不是,http://en.wikipedia.org/wiki/Bézier_curve有一些很好的定义和动画。 - Nate Symer
https://iosdevcenters.blogspot.com/2018/02/how-to-set-roundcorner-radius-on-view.html - Bhadresh
请查看我的答案:https://dev59.com/I10b5IYBdhLWcg3wGN0s#50396485 - wcarhart
显示剩余2条评论
31个回答

0
在Swift 4.2中,可以通过以下方式使用@IBDesignable创建它:
@IBDesignable

class DesignableViewCustomCorner: UIView {

    @IBInspectable var cornerRadious: CGFloat = 0 {
        didSet {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadious, height: cornerRadious))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接