Search code examples
swiftuiviewlayershadowuibezierpath

shadow on bezierpath view adds weird strokes to corners


I wanted to recreate the AppStore's "today" cards with rounded corners and a light drop shadow.

I created a path, a maskLayer and a separate shadowLayer, which – according to several sources – is the way of doing it.

The problem, however, is that my lovely rounded rectangle with a shadow has got some gray strokes at it corners. How can I solve this? I tried different shadow opacities and different radii. It didn't solve my problem.

Here you can see my screenshots and my code below.

override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view

        // create sample view and add to view hierarchy
        let bigTeaser = UIView(frame: CGRect(x: 16, y: 200, width: 343, height: 267))
        bigTeaser.backgroundColor = UIColor.white
        view.addSubview(bigTeaser)

        // create the path for the rounded corners and the shadow
        let roundPath = UIBezierPath(roundedRect: bigTeaser.bounds, cornerRadius: 20)

        // create maskLayer
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bigTeaser.bounds
        maskLayer.path = roundPath.cgPath
        bigTeaser.layer.mask = maskLayer

        // create shadowLayer
        let shadowLayer = CAShapeLayer()
        shadowLayer.path = roundPath.cgPath
        shadowLayer.frame = bigTeaser.frame
        shadowLayer.shadowOpacity = 0.3
        shadowLayer.shadowRadius = 24
        shadowLayer.shadowColor = UIColor.black.cgColor
        shadowLayer.shadowOffset = CGSize(width: 0, height: 2)

        // insert layers
        bigTeaser.superview!.layer.insertSublayer(shadowLayer, below: bigTeaser.layer)

    }

radius == 20

radius == 40


Solution

  • If you replace:

    shadowLayer.path = roundPath.cgPath
    

    to

    shadowLayer.shadowPath = roundPath.cgPath
    

    The ugly borders will magically disappear.