为CGMutablePath绘制阴影,不是封闭的,只是一条线

时间:2018-07-18 17:28:35

标签: macos calayer nsview shadow

我有一个Track.getShadowPath()函数,它返回一个CGMutablePath

函数返回CGMutablePath

static func getShadowPath() -> CGMutablePath{

    let trackPath = CGMutablePath()

    let initPoint = Track.tracks.first?.initPoint


    let heigthShift = CGPoint(x: 0, y: 100)
    trackPath.move(to: initPoint! - heigthShift)

    var yShift = CGPoint(x: 0, y: 0)

    for track:Track in Track.tracks{

        let q = track.getQuadrant()
        if(q == 2 || q == 5){
            yShift.y = yShift.y + track.endPoint.y - track.initPoint.y
        }
        else {
            trackPath.addLine(to: track.endPoint - heigthShift - yShift)
        }
    }

    return trackPath
}

然后将此路径添加到CAShapeLayer,并将该层作为子层添加到我的视图中。我希望此路径具有阴影方面。但是,当渲染时,它会产生阴影,好像路径已关闭。我怎样才能达到目的?

NSView

class DemoView: NSView {
    var trackShape:CAShapeLayer!
    var trackShadowShape:CAShapeLayer!

override init(frame: CGRect){
    super.init(frame: frame)

    trackShape = CAShapeLayer()

    trackShape.strokeColor = NSColor.black.cgColor
    trackShape.lineWidth = 3
    trackShape.lineJoin = kCALineJoinBevel
    trackShape.lineCap = kCALineCapRound
    trackShape.fillColor = nil

    trackShadowShape = CAShapeLayer()

    trackShadowShape.lineWidth = 14
    trackShadowShape.lineJoin = kCALineJoinBevel
    trackShadowShape.lineCap = kCALineCapRound
    trackShadowShape.fillColor = nil
    trackShadowShape.shadowColor = NSColor.blue.cgColor
    trackShadowShape.shadowRadius = 10

    self.layer?.addSublayer(trackShadowShape)
    self.layer?.addSublayer(trackShape)
 }

func redrawTrack(){
    trackShape.path = Track.getCompletePath()
    trackShadowShape.shadowPath = Track.getShadowPath()
    trackShadowShape.shadowRadius = 20
    trackShadowShape.shadowOpacity = 1
    trackShadowShape.fillColor = NSColor.clear.cgColor
    trackShadowShape.lineWidth = 10

 }
}

意外结果

Non-expected result

1 个答案:

答案 0 :(得分:0)

我使用以下方法解决了这个问题:

copy(strokingWithWidth lineWidth: CGFloat, lineCap: CGLineCap, lineJoin: CGLineJoin, miterLimit: CGFloat, transform: CGAffineTransform = default)

根据文档

  

返回与绘制路径等效的新路径   坚实的行程。

因此,基本上它会创建一个新的CGPath,它是您提供的路径的笔触轮廓,并具有所需的宽度,上限等。 :

getShadowPath

然后,我将该路径用作图层的shadowPath。现在的结果是预期的结果:

Expected results

可以在here

中找到与Objective-c类似的答案