Create a rectangle with just two rounded corners in swift?

后端 未结 15 2980
南笙
南笙 2020-11-28 03:14

I need to create a rectangle that have just two rounded corners in swift (Objective C code also ok).

At the moment my code is creating two rectangles with



        
15条回答
  •  北海茫月
    2020-11-28 03:41

    In Swift 2.3 you could do so by

    let maskPath = UIBezierPath(roundedRect: anyView.bounds,
                byRoundingCorners: [.BottomLeft, .BottomRight],
                cornerRadii: CGSize(width: 10.0, height: 10.0))
    
    let shape = CAShapeLayer()
    shape.path = maskPath.CGPath
    view.layer.mask = shape
    

    In Objective-C you could use the UIBezierPath class method

    bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
    

    example implementation-

    // set the corner radius to the specified corners of the passed container
    - (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
    {
        UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                      byRoundingCorners:corners
                                                            cornerRadii:CGSizeMake(10.0, 10.0)];
        CAShapeLayer *shape = [[CAShapeLayer alloc] init];
        [shape setPath:rounded.CGPath];
        view.layer.mask = shape;
    }
    

    and call the above method as-

    [self setMaskTo:anyView byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight];
    

提交回复
热议问题