Tal Zion
Tal Zion

Reputation: 6526

How to add a single smooth line with multiple CGPoint Swift 2.0

I have this function that takes an Array[CGPoint] and I am trying to create a single trend. I can't get it to be a smooth line through the array of points, when I use the moveToPoint() function after each point, I get this black line in the background. This is my code and images of the output:

class func drawLineThroughPoint(start : CGPoint, throughPoint through: [CGPoint], endPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    let path = UIBezierPath()
    path.moveToPoint(start)
    for (_, point) in EnumerateSequence(through) {
        path.addLineToPoint(point)
        //path.moveToPoint(point) MARK: See image with moveToPoint
        path.moveToPoint(point) //MARK: See image without moveToPoint
    }
    path.addLineToPoint(end)

    //design path in layer
    //design path in layer
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath
    shapeLayer.strokeColor = lineColor.CGColor
    shapeLayer.shadowColor = lineColor.CGColor
    shapeLayer.shadowOffset = CGSize(width: 0, height: 2)
    shapeLayer.shadowOpacity = 0.95
    shapeLayer.shadowRadius = 5
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineCap = kCALineCapRound

    shapeLayer.lineWidth = 10.0

    view.layer.addSublayer(shapeLayer)
}

With path.moveToPoint()

Without path.moveToPoint()

Without path.moveToPoint()

With path.moveToPoint()

Upvotes: 0

Views: 888

Answers (2)

Hamish
Hamish

Reputation: 80811

Without the moveToPoint in the for loop is the correct approach.

If you use moveToPoint in the for loop, you're creating a new line segment for each section of the path, hence why it looked disconnected.

Your "black line in the background" in the first image is just the CAShapeLayer trying to fill the area covered by the path.

You can remedy this by simply setting the fillColor of the CAShapeLayer to clearColor.

shapeLayer.fillColor = UIColor.clearColor().CGColor

This gives me the following result:

enter image description here

Upvotes: 1

GaétanZ
GaétanZ

Reputation: 4930

Change the lineJoinStyle property of your path or use the addCurveToPoint: method.

Upvotes: 0

Related Questions