目前,我正在MKMapView上跟踪我的位置。我的目标是绘制与从跟踪位置创建的MKPolyline相同的贝塞尔曲线路径。

我尝试过的是:将所有位置坐标存储在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
    }
}

我能够将点输出到从convert(_ :)方法存储的控制台(不确定它们是否正确)。但是,在bezierPathView上没有输出,这是空白色背景视图控制器的结果。

最佳答案

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

我建议您简化您的项目,例如使用绝对适合您的视图的预定义点数组。例如,对于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)
]

使用清晰可见的颜色(例如黑色和黄色)作为描边和填充。

确保您的路径已正确添加到视图中,例如:
let path = UIBezierPath(points: points)

let shapeLayer = CAShapeLayer(path: path, lineColor: UIColor.blue, fillColor: UIColor.lightGray)

view.layer.addSublayer(shapeLayer)

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

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

07-24 09:55