如何绘制虚线箭头?

How to draw dashed arrow?

我想画这样的箭头:

我找到了如何只绘制实线箭头here,但我不知道如何像上面那样绘制箭头。

解法:

对我来说,我最终得到了以下代码:

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)
}

这是我为在操场上获得此代码而编写的此类 ArrowView 的代码:

//箭头视图

class ArrowView : UIView {


var dashWidth :CGFloat = 3.0
var dashGap : CGFloat = 3.0
var arrowThickNess : CGFloat = 2.0
var arrowLocationX : CGFloat = 0.0
//MARK:

override func drawRect(rect: CGRect) {

    //Compute the dashPath 

    let path = UIBezierPath()

    //Compute the mid y, path height
    let midY = CGRectGetMidY(frame)
    let pathHeight = CGRectGetHeight(frame)


    path.moveToPoint(CGPointMake(frame.origin.x, midY))
    path.addLineToPoint(CGPointMake(frame.origin.x + frame.size.width - dashWidth , midY))
    path.lineWidth = arrowThickNess

    let dashes: [CGFloat] = [dashWidth, dashGap]
    path.setLineDash(dashes, count: dashes.count, phase: 0)


    //Arrow 

    let arrow = UIBezierPath()

    arrow.lineWidth = arrowThickNess

    arrow.moveToPoint(CGPointMake(frame.origin.x + arrowLocationX , midY))
    arrow.addLineToPoint(CGPointMake(frame.origin.x + frame.size.width -  arrowThickNess/2 - 18, 0))
    arrow.moveToPoint(CGPointMake(frame.origin.x + arrowLocationX , midY))
    arrow.addLineToPoint(CGPointMake(frame.origin.x + frame.size.width - arrowThickNess/2 - 18 , pathHeight))
    arrow.lineCapStyle = .Square


    UIColor.whiteColor().set()
    path.stroke()
    arrow.stroke()

 }

}


let arrowView = ArrowView(frame: CGRect(x: 0, y: 0, width: 210, height: 20))
arrowView.dashGap = 10
arrowView.dashWidth = 5
arrowView.arrowLocationX = 202

arrowView.setNeedsDisplay()

基本上,您将需要创建一个带有所需破折号的贝塞尔曲线路径,并且您需要将破折号作为浮点值数组提供。在此贝塞尔路径的末尾,您需要绘制另一个表示箭头的贝塞尔路径。

输出:-