如何遍历坐标数组来绘制 CGPath?

How to iterate through an array of coordinates to draw a CGPath?

我们有一个坐标数组,我们想遍历它们来绘制一条路径。这是硬编码值的外观:

 func createPath(){
        path.move(to: CGPoint(x: 32.7915055, y: -96.8028408))//1
        path.addLine(to: CGPoint(x: 32.79174845, y: -96.80252195))
        path.addLine(to: CGPoint(x: 32.7919914, y: -96.8022031))//2
        path.addLine(to: CGPoint(x: 32.791501100000005, y: -96.80235195))
        path.addLine(to: CGPoint(x: 32.7910108, y: -96.8025008))//3
        path.addLine(to: CGPoint(x: 32.791301700000005, y: -96.8020985))
        path.addLine(to: CGPoint(x: 32.7915926, y: -96.8016962))//4
        path.addLine(to: CGPoint(x: 32.79154905, y: -96.8022685))
        
    }

但我们正在尝试不进行硬编码,而是创建一个采用坐标数组的函数,如下所示:

 func create(coordinates: [CLLocationCoordinate2D]) {
        for coordinate in coordinates {
            path.move(to: CGPoint(x: coordinate.x, y:coordinate.y))//error
            path.addLine(to: CGPoint(x: coordinate.x, y: coordinate.y))//error
        }
    }

问题是如何获取数组中“path.move”的第一个坐标,然后将附加坐标用于函数的“path.addLine”部分?

枚举数组并测试其索引:

  for (index, coordinate) in coordinates.enumerated() {
        if index == 0 {
            path.move(to: CGPoint(x: coordinate.longitude, y:coordinate. latitude))
        } else {
            path.addLine(to: CGPoint(x: coordinate.longitude, y: coordinate.latitude))
        }
  }

也注意到 CLLocationCoordinate2D 没有 x 也没有 ylongitudelatitude

有一种方便的 CGContext.addLines(between:) 方法可以做到这一点。这是文档中的描述:

Calling this convenience method is equivalent to calling the move(to:) method with the first value in the points array, then calling the addLine(to:) method for each subsequent point until the array is exhausted. After calling this method, the path's current point is the last point in the array.

用法:

let cgPoints = coordinates.map { CGPoint(x: [=10=].longitude, y: [=10=].latitude) } 
ctx.addLines(between: cgPoints)