Create a rectangle with just two rounded corners in swift?

后端 未结 15 3029
南笙
南笙 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条回答
  •  旧时难觅i
    2020-11-28 04:04

    Building on top of Sanjay's excellent answer, I wrote a quick CALayer extension for Swift 2.3, in case you need to do this sort of "only round some corners" thing more than once.

    extension CALayer {
      func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: bounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
    
        let shape = CAShapeLayer()
        shape.path = maskPath.CGPath
        mask = shape
      }
    }
    

    Usage:

    myView.layer.roundCorners([.TopLeft, .TopRight], radius: myCornerRadius)
    

    Swift 3.0 (In this example the bounds came from the view not from the layer. Using the bounds from the view make this code to work with views in a UITableViewCell.):

    func roundCorners(corners: UIRectCorner, radius: CGFloat, viewBounds: CGRect) {
    
        let maskPath = UIBezierPath(roundedRect: viewBounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
    
        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        mask = shape
    }
    

    Usage:

    myView.layer.roundCorners(corners: [.topLeft, .topRight], radius: myCornerRadius, viewBounds: bounds)
    

提交回复
热议问题