Andrey M. Andrey M. - 3 months ago 120
Swift Question

How to draw dashed arrow?

I want to draw arrow like this:

enter image description here

I found how to draw just solid arrow here, but i don't know how to draw arrow like above.

Solution:

For me I ended up with code below:

func addArrowOntoView(view: UIView, startPoint: CGPoint, endPoint: CGPoint, color: UIColor) {
let line = UIBezierPath()
line.moveToPoint(startPoint)
line.addLineToPoint(endPoint)

let arrow = UIBezierPath()

arrow.moveToPoint(endPoint)
arrow.addLineToPoint(CGPointMake(endPoint.x - 5, endPoint.y - 4))
arrow.moveToPoint(endPoint)
arrow.addLineToPoint(CGPointMake(endPoint.x - 5, endPoint.y + 4))
arrow.lineCapStyle = .Square

let sublayer = CAShapeLayer()
sublayer.path = line.CGPath
view.layer.addSublayer(sublayer)

//add Line
let lineLayer = CAShapeLayer()
lineLayer.path = line.CGPath
lineLayer.strokeColor = color.CGColor
lineLayer.lineWidth = 1.0
lineLayer.lineDashPattern = [5, 3]
view.layer.addSublayer(lineLayer)

//add Arrow
let arrowLayer = CAShapeLayer()
arrowLayer.path = arrow.CGPath
arrowLayer.strokeColor = color.CGColor
arrowLayer.lineWidth = 1.0
view.layer.addSublayer(arrowLayer)
}

Answer

Here is a code that I wrote to get this in a playground:

import UIKit
import XCPlayground

let path = UIBezierPath()
path.moveToPoint(CGPointMake(10, 10))
path.addLineToPoint(CGPointMake(290, 10))
path.lineWidth = 4

let dashes: [CGFloat] = [path.lineWidth*2, path.lineWidth*2]
path.setLineDash(dashes, count: dashes.count, phase: 0)

//Arrow 
let arrow = UIBezierPath()

arrow.lineWidth = 3

arrow.moveToPoint(CGPointMake(290 + path.lineWidth - arrow.lineWidth/2, 10))
arrow.addLineToPoint(CGPointMake(280, 2))
arrow.moveToPoint(CGPointMake(290 + path.lineWidth - arrow.lineWidth/2, 10))
arrow.addLineToPoint(CGPointMake(280, 18))
arrow.lineCapStyle = .Square


UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 20), false, 2)

UIColor.whiteColor().set()
path.stroke()
arrow.stroke()
//Arrow end

let image = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

Basically you will need to create a bezier path with required line dashes and you will need to supply the dashes as an array of float values. At the end of this bezier path, you will need to draw another bezier path representing the arrow.

Output:-

enter image description here