lif*_*ott 5 mapkit polyline ios uibezierpath swift
目前我正在 MKMapView 上跟踪我的位置。我的目标是绘制一条与从跟踪位置创建的 MKPolyline 相同的贝塞尔路径。
我尝试过的是:将所有位置坐标存储在 CLLocation 数组中。迭代该数组并将纬度/经度坐标存储在 CLLocationCooperative2D 数组中。然后确保折线位于屏幕视图中,然后转换 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
}
}
Run Code Online (Sandbox Code Playgroud)
我能够将从 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)
]
Run Code Online (Sandbox Code Playgroud)
使用清晰可见的颜色,例如黑色和黄色作为描边和填充。
确保您的路径已正确添加到视图中,例如:
let path = UIBezierPath(points: points)
let shapeLayer = CAShapeLayer(path: path, lineColor: UIColor.blue, fillColor: UIColor.lightGray)
view.layer.addSublayer(shapeLayer)
Run Code Online (Sandbox Code Playgroud)
在 Xcode 的 Interface Builder 中检查包含视图的控制器。在调试视图层次结构函数中:
| 归档时间: |
|
| 查看次数: |
1985 次 |
| 最近记录: |