Swift draw shadow to a uibezier path

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 pretty simple :

        let borderLine = UIBezierPath()
        borderLine.moveToPoint(CGPoint(x:0, y: y! - 1))
        borderLine.addLineToPoint(CGPoint(x: x!, y: y! - 1))
        borderLine.lineWidth = 2

        let shadowLayer = CAShapeLayer()
        shadowLayer.shadowOpacity = 1
        shadowLayer.shadowOffset = CGSize(width: 0,height: 1)
        shadowLayer.shadowColor = UIColor.redColor().CGColor
        shadowLayer.shadowRadius = 1
        shadowLayer.masksToBounds = false
        shadowLayer.shadowPath = borderLine.CGPath


What am I doing wrong as I dont seem to see anything wrong but of course I am wrong since no shadow appears. The function is drawRect, basic UIVIew no extra anything in there, x and y are the width and height of the frame.
Many thanks in advance!

  • How to add a border to a circular image with mask
  • Drop a shadow to right and bottom of uiview
  • Solid Shadow in All Directions
  • Animating CALayer's shadowPath property
  • How to rounded the corners when I draw rectangle using UIBezierPath points
  • iOS: CAShape Layer Path Transformation
  • 2 Solutions Collect From Internet About “Swift draw shadow to a uibezier path”

    I take this example straight from my PaintCode-app. Hope this helps.

    //// General Declarations
    let context = UIGraphicsGetCurrentContext()
    //// Shadow Declarations
    let shadow = UIColor.blackColor()
    let shadowOffset = CGSizeMake(3.1, 3.1)
    let shadowBlurRadius: CGFloat = 5
    //// Bezier 2 Drawing
    var bezier2Path = UIBezierPath()
    bezier2Path.moveToPoint(CGPointMake(30.5, 90.5))
    bezier2Path.addLineToPoint(CGPointMake(115.5, 90.5))
    CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius,  (shadow as UIColor).CGColor)
    bezier2Path.lineWidth = 1

    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
    let shadowSubLayer = createShadowLayer()
    shadowSubLayer.insertSublayer(line, at: 0)