如何在UIView中绘制与MKPolyline相同的UIBezierPath

目前我正在跟踪我的位置在一个MKMapView。 我的目标是绘制一个与从追踪位置创build的MKPolyline相同的贝塞尔path。

我所尝试的是:将所有位置坐标存储在CLLocation数组中。 迭代该数组,并将经纬度坐标存储在CLLocationCoordinate2D数组中。 然后确保多段线在屏幕的视图中,然后转换CGPoints中的所有位置坐标。

当前尝试:

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

我能够输出到转换(_ :)方法存储的控制台(不知道它们是否正确)。 然而bezierPathView没有输出,导致一个空白的背景视图控制器。

你的扩展工作正常。 问题可能出现在将图层添加到视图的代码中(您不会显示)。

我build议你简化你的项目,例如使用预定义的点数组合,绝对适合你的观点。 例如,对于500像素宽,300像素高的视图,您可以使用如下所示的内容:

 let points = [ CGPoint(x: 10, y: 10), CGPoint(x: 490, y: 10), CGPoint(x: 490, y: 290), CGPoint(x: 10, y: 290), CGPoint(x: 10, y: 10) ] 

使用清晰可见的颜色,如黑色和黄色,为您的笔画和填充。

确保您的path正确添加到视图,例如:

 let path = UIBezierPath(points: points) let shapeLayer = CAShapeLayer(path: path, lineColor: UIColor.blue, fillColor: UIColor.lightGray) view.layer.addSublayer(shapeLayer) 

在Xcode的Interface Builder中检查包含视图的控​​制器。 在debugging视图层次结构函数中:

在这里输入图像说明