Swift draw shadow to a uibezier path

浪尽此生 提交于 2019-12-04 13:56:53

问题



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
        UIColor.blackColor().setStroke()
        borderLine.stroke()

        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

        self.layer.addSublayer(shadowLayer)

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!


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/29126271/swift-draw-shadow-to-a-uibezier-path

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