在贝塞尔弧内绘制子层

Drawing sublayers inside a bezier Arc

我正在尝试在圆弧内绘制一系列垂直线,但我无法做到这一点。我正在尝试使用 CAShapeLayers 执行此操作,最终结果看起来像这样。

我知道如何使用 CAShapeLayers 绘制弧线和线段,但我似乎无法弄清楚如何在 CAShapeLayer

中绘制垂直线

我最初的方法是子class CAShapeLayer 并在子class 中尝试绘制垂直线。但是,我没有得到想要的结果。这是我的代码,用于向贝塞尔曲线点添加一条线并尝试添加子层。

class CustomLayer : CAShapeLayer {
    override init() {
       super.init()
           }

    func drawDividerLayer(){
        print("Init has been called in custom layer")
        print("The bounds of the custom layer is: \(bounds)")
        print("The frame of the custom layer is: \(frame)")

        let bezierPath = UIBezierPath()


        let dividerShapeLayer = CAShapeLayer()
        dividerShapeLayer.strokeColor = UIColor.redColor().CGColor
        dividerShapeLayer.lineWidth = 1
        let startPoint = CGPointMake(5, 0)
        let endPoint = CGPointMake(5, 8)

        let convertedStart = convertPoint(startPoint, toLayer: dividerShapeLayer)
        let convertedEndPoint = convertPoint(endPoint, toLayer: dividerShapeLayer)

        bezierPath.moveToPoint(convertedStart)
        bezierPath.addLineToPoint(convertedEndPoint)

        dividerShapeLayer.path = bezierPath.CGPath

        addSublayer(dividerShapeLayer)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class DrawView : UIView {

    var customDrawLayer : CAShapeLayer!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //drawLayers()
    }

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
    }

    func drawLayers() {
        let bezierPath = UIBezierPath()

        let startPoint = CGPointMake(5, 35)
        let endPoint  = CGPointMake(100, 35)

        bezierPath.moveToPoint(startPoint)
        bezierPath.addLineToPoint(endPoint)

        let  customLayer = CustomLayer()
        customLayer.frame = CGPathGetBoundingBox(bezierPath.CGPath)
        customLayer.drawDividerLayer()


        customLayer.strokeColor = UIColor.blackColor().CGColor
        customLayer.opacity = 0.5
        customLayer.lineWidth = 8
        customLayer.fillColor = UIColor.clearColor().CGColor

        layer.addSublayer(customLayer)
        customLayer.path = bezierPath.CGPath

    }

然而这段代码产生了这张图片:

看来我确实遇到了坐标 space problem/bounds/frame 的问题,但我不太确定。我希望它工作的方式是从 superLayer 的顶部绘制到 CustomLayer class 内部的 superLayer 的底部。但不仅如此,这必须使用 bezier 路径 addArcWithCenter: 方法才能工作,我还没有使用它,因为我试图先解决这个问题。任何帮助,将不胜感激。

绘制由线组成的圆弧的最简单方法是使用 lineDashPattern:

let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)
let arc = CAShapeLayer()
arc.path = path.CGPath
arc.lineWidth = 50
arc.lineDashPattern = [4,15]
arc.strokeColor = UIColor.lightGrayColor().CGColor
arc.fillColor = UIColor.clearColor().CGColor
view.layer.addSublayer(arc)

所以这是上面显示的虚线弧下方的蓝色弧。显然,为了可见性,我放大了它,但它说明了这个想法。