Swift draw shadow to a uibezier path

前端 未结 3 1081
悲&欢浪女
悲&欢浪女 2021-02-06 16:01


I have a strange question. Even though I did read a lot of tutorials on how to do this, the final result only shows the bezier line, not any shadow whatsoever. My code is

3条回答
  •  悲哀的现实
    2021-02-06 16:37

    I prefer the way to add a shadow-sublayer. You can easily use the following function (Swift 3.0):

    func createShadowLayer() -> CALayer {
        let shadowLayer = CALayer()
        shadowLayer.shadowColor = UIColor.red.cgColor
        shadowLayer.shadowOffset = CGSize.zero
        shadowLayer.shadowRadius = 5.0
        shadowLayer.shadowOpacity = 0.8
        shadowLayer.backgroundColor = UIColor.clear.cgColor
        return shadowLayer
    }
    

    And finally, you just add it to your line path (CAShapeLayer):

    let line = CAShapeLayer()
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: 50, y: 100))
    path.addLine(to: CGPoint(x: 100, y: 50))
    line.path = path.cgPath
    line.strokeColor = UIColor.blue.cgColor
    line.fillColor = UIColor.clear.cgColor
    line.lineWidth = 2.0
    view.layer.addSublayer(line)
    
    let shadowSubLayer = createShadowLayer()
    shadowSubLayer.insertSublayer(line, at: 0)
    view.layer.addSublayer(shadowSubLayer)
    

提交回复
热议问题