iosswiftuiviewuibezierpathcurve

How to draw center curve in UIView?


How to create a smooth top center inward curve in a UIView in Swift (using UIBezierPath)?

This does create a curve, but it doesn’t look smooth or natural. It either appears too sharp or not deep enough, depending on how I tweak curveHeight and curveWidth. Also, the shadow doesn’t always match the shape well.

import UIKit

class CurvedView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    private func setupView() {
        backgroundColor = .white
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.25
        layer.shadowOffset = CGSize(width: 0, height: 10)
        layer.shadowRadius = 10
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        applyCurve()
    }

    private func applyCurve() {
        let path = UIBezierPath()

        let width = bounds.width
        let height = bounds.height

        let curveHeight: CGFloat = 60
        let curveWidth: CGFloat = 120

        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: (width - curveWidth) / 2, y: 0))

        path.addQuadCurve(
            to: CGPoint(x: (width + curveWidth) / 2, y: 0),
            controlPoint: CGPoint(x: width / 2, y: curveHeight)
        )

        path.addLine(to: CGPoint(x: width, y: 0))
        path.addLine(to: CGPoint(x: width, y: height))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.close()

        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}

Curved View

Can anyone help me to achieve this curve?


Solution

  • I wrote a demo several years ago that generated a shape similar to what you show. It builds the shape as a CGPath using the function addArc(tangent1End:tangent2End:radius:transform:)

    Below is the shape it creates. You should be able to adapt it to your needs.

    enter image description here

    I just uploaded the project to Github. You can find it at the link below:

    https://github.com/DuncanMC/ShapeWithTab