在贝塞尔弧内绘制子层

时间:2015-12-08 17:59:52

标签: ios swift uiview cashapelayer

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

enter image description here

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

内绘制垂直线

我最初的方法是继承CAShapeLayer并在子类中尝试绘制垂直线。但是,我没有得到预期的结果。这是我的代码,用于向bezier点添加一行并尝试添加子图层。

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

    }

但是,此代码会生成此图像:

enter image description here

我肯定有一个坐标空间问题/边界/框架问题,但我不太确定。我希望它的工作方式是从superLayer的顶部绘制到CustomLayer类内部的superLayer底部。但不仅如此,这必须使用贝塞尔路径addArcWithCenter:方法,我还没有达到这个方法,因为我试图首先解决这个问题。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:3)

绘制由线条组成的弧线的最简单方法是使用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)

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

enter image description here