Cómo dibujar UIBezierPath idéntico a MKPolyline en una UIView
Actualmente estoy rastreando mi ubicación en un MKMapView. Mi objetivo es dibujar un camino bezier idéntico a un MKPolyline creado a partir de ubicaciones rastreadas.
Lo que he intentado es: almacenar todas las coordenadas de ubicación en una matriz CLLocation. Itere sobre esa matriz y almacene las coordenadas lat / lng en una matriz CLLocationCoordinate2D. Luego, asegúrese de que la polilínea esté en la vista de la pantalla para luego convertir todas las coordenadas de ubicación en CGPoints.
Intento actual:
@IBOutlet weak var bezierPathView: UIView!
var locations = [CLLocation]() // values from didUpdateLocation(_:)
func createBezierPath() {
bezierPathView.isHidden = false
var coordinates = [CLLocationCoordinate2D]()
for location in locations {
coordinates.append(location.coordinate)
}
let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
fitPolylineInView(polyline: polyline)
let mapPoints = polyline.points()
var points = [CGPoint]()
for point in 0...polyline.pointCount
{
let coordinate = MKCoordinateForMapPoint(mapPoints[point])
points.append(mapView.convert(coordinate, toPointTo: polylineView))
}
print(points)
let path = UIBezierPath(points: points)
path.lineWidth = 2.0
path.lineJoinStyle = .round
let layer = CAShapeLayer(path: path, lineColor: UIColor.red, fillColor: UIColor.black)
bezierPathView.layer.addSublayer(layer)
}
extension UIBezierPath {
convenience init(points:[CGPoint])
{
self.init()
//connect every points by line.
//the first point is start point
for (index,aPoint) in points.enumerated()
{
if index == 0 {
self.move(to: aPoint)
}
else {
self.addLine(to: aPoint)
}
}
}
}
extension CAShapeLayer
{
convenience init(path:UIBezierPath, lineColor:UIColor, fillColor:UIColor)
{
self.init()
self.path = path.cgPath
self.strokeColor = lineColor.cgColor
self.fillColor = fillColor.cgColor
self.lineWidth = path.lineWidth
self.opacity = 1
self.frame = path.bounds
}
}
Puedo mostrar los puntos en la consola que se almacenaron desde el método de conversión (_ :) (no estoy seguro de si son correctos). Sin embargo, no hay salida en bezierPathView, lo que da como resultado un controlador de vista de fondo blanco y vacío.