Swift draw shadow to a uibezier path

廉价感情. 提交于 2019-12-03 09:42:34

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))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius,  (shadow as UIColor).CGColor)
UIColor.blackColor().setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
CGContextRestoreGState(context)

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!