简体   繁体   中英

Add Shadow to CAShapeLayer with UIBezierPath

need some help adding a drop shadow to a line created with a CAShapeLayer / UIBezierPath

This code snippet produces the following line shape as in the screenshot below

        let bounds = UIScreen.main.bounds
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 10.0
        
        shapeLayer.frame = CGRect(x: 0, y: 0 , width: bounds.width, height: bounds.width)
        
        shapeLayer.lineWidth = 5.0
        shapeLayer.strokeColor = UIColor.red.cgColor
        

        let offset : CGFloat = 20
        let arcCenter = shapeLayer.position
        let radius = shapeLayer.bounds.size.width / 2.0 - offset
        let startAngle = CGFloat(0.0)
        let endAngle = CGFloat(1.0 * .pi)
        
        let circlePath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

        
        shapeLayer.shadowOffset = CGSize(width: 0, height: 0)
        shapeLayer.shadowColor = UIColor.red.cgColor
        shapeLayer.shadowOpacity = 1.0
        shapeLayer.shadowRadius = 25
    
        shapeLayer.path = circlePath.cgPath

在此处输入图像描述

As you can see the shadow surrounds the outer part of the semi-circle shape.

Could anyone give me any hints on adding a drop shadow around the line only ?

Output :

在此处输入图像描述

UIView Extension :

extension UIView {
    func renderCircle() {
        let semiCircleLayer = CAShapeLayer()
        
        let center = CGPoint (x: self.frame.size.width / 2, y: self.frame.size.height / 2)
        let circleRadius = self.frame.size.width / 2
        let circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: CGFloat(Double.pi * 2), endAngle: CGFloat(Double.pi), clockwise: true)
        
        semiCircleLayer.path = circlePath.cgPath
        semiCircleLayer.strokeColor = UIColor.red.cgColor
        semiCircleLayer.fillColor = UIColor.clear.cgColor
        semiCircleLayer.lineWidth = 8
        semiCircleLayer.shadowColor = UIColor.red.cgColor
        semiCircleLayer.shadowRadius = 25.0
        semiCircleLayer.shadowOpacity = 1.0
        semiCircleLayer.shadowPath = circlePath.cgPath.copy(strokingWithWidth: 25, lineCap: .round, lineJoin: .miter, miterLimit: 0)

        semiCircleLayer.shadowOffset = CGSize(width: 1.0, height: 1.0)
        self.layer.addSublayer(semiCircleLayer)
    }
}

Usage :

semiCircleView.renderCircle()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM