iosswiftcore-graphics

Create a rectangle with just two rounded corners in swift?


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

CGPathCreateWithRoundedRect(CGRectMake(0, 0, 30, 60), 5, 5, nil);

and

CGPathCreateWithRoundedRect(CGRectMake(0, 0, 30, 60), 0, 0, nil);

and merging them (to have two right angle corners and two rounded ones) but I am not happy with the code and I am pretty sure there should be much better ways to do it.

I am new to iOS and graphical development and swift.


Solution

  • 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];