You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MKMapSnapshotter生成地图快照时如何避免起点终点连线

解决MKMapSnapshotter路线快照闭环问题

你的代码里的路径绘制逻辑本身不会自动闭合路线,出现起点终点连成闭环的情况,大概率是**getTrackPointForPolyline()返回的坐标数组中,首尾坐标完全重复**,导致最后一段线从终点连回了起点(加上round风格的线帽/线连接,视觉上更像闭环)。

以下是解决方案:

方案:移除首尾重复的坐标(推荐)

在处理坐标数组时,先检查并移除首尾重复的元素,从根源避免闭环:

修改后的完整代码

func saveMapViewAsImage(region: MKCoordinateRegion, size: CGSize) {
    let options = MKMapSnapshotter.Options()
    options.region = region
    options.size = size
    options.mapType = .standard

    MKMapSnapshotter(options: options).start { snapshot, error in
        guard let snapshot = snapshot else { return }
        
        let mapImage = snapshot.image
        
        let finalImage = UIGraphicsImageRenderer(size: size).image { _ in
            mapImage.draw(at: .zero)
                
            // 获取轨迹坐标并处理首尾重复
            var coordinates = self.getTrackPointForPolyline()
            // 当数组长度大于1且首尾坐标相同时,移除最后一个元素
            if coordinates.count > 1, coordinates.first == coordinates.last {
                coordinates.removeLast()
            }
            guard coordinates.count > 1 else { return }
            
            // 转换为快照上的CGPoint
            let points = coordinates.map { coordinate in
                snapshot.point(for: coordinate)
            }

            // 绘制路线
            let path = UIBezierPath()
            path.lineWidth = K.Map.routeLineWidth * 0.5
            path.lineCapStyle = .round
            path.lineJoinStyle = .round

            path.move(to: points[0])
            for index in 1..<points.count {
                path.addLine(to: points[index])
            }

            K.Map.routeLineColor.withAlphaComponent(0.75).setStroke()
            path.stroke()
        }

        // 保存图片
        self.saveRenderedImageToDocumentDirectory(image: finalImage)
    }
}

补充说明

  • 如果你的轨迹是单程路线(比如从A到B),确保数据源不包含首尾重复坐标是最根本的解决方式
  • 如果是往返路线(A到B再回到A),闭环是合理效果,这种情况不需要处理

内容的提问来源于stack exchange,提问作者Hoyeon Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:05:39