Mapbox 10版本MGLAnnotationView替代方案及脉动标注效果实现咨询
Mapbox 10 标注脉动效果实现方案
替代组件说明
Mapbox 10 废弃了原有的 MGLAnnotationView 体系,对应的官方替代组件是View Annotation,它保留了原生UI视图自定义的所有灵活性,支持直接添加自定义CALayer实现动画,完全可以满足你现有的脉动标注核心功能需求。
实现代码
原有脉动动画逻辑(包括你用到的CustomPulseLayer CAReplicatorLayer动画)可以100%复用,只需要调整标注的创建和挂载逻辑即可,适配后的代码如下:
// 自定义标注视图,原有视图逻辑基本完全复用 class CustomPulseAnnotationView: UIView { let customPulse = CustomPulseLayer() // 原有脉动层直接复用 private let pointImageView: UIImageView init(reuseId: String, showPulse: Bool) { let frame = CGRect(x: 0, y: 0, width: 24, height: 24) // 图片加载逻辑和原有一致 pointImageView = UIImageView(frame: frame) pointImageView.image = imageBasedOnIdentifier(reuseId) super.init(frame: frame) layer.cornerRadius = bounds.width / 2 backgroundColor = .systemBlue addSubview(pointImageView) if showPulse { layer.addSublayer(customPulse) customPulse.start() // 原有脉动动画启动逻辑直接复用 } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 同步调整脉动层布局 override func layoutSubviews() { super.layoutSubviews() customPulse.frame = bounds } } // 标注添加到地图的逻辑 func addPulseAnnotation(mapView: MapView, coordinate: CLLocationCoordinate2D, reuseId: String, showPulse: Bool) { let customAnnotationView = CustomPulseAnnotationView(reuseId: reuseId, showPulse: showPulse) // 配置标注参数 let options = ViewAnnotationOptions( geometry: Point(coordinate), // 绑定标注地理坐标,替代原有MGLPointFeature allowOverlap: false, anchor: .center ) // 把自定义视图添加为地图的View Annotation try? mapView.viewAnnotations.add(customAnnotationView, options: options) }
注意事项
- 原有
MGLPointFeature的功能现在直接用Point类型传递坐标即可,不需要额外封装Feature对象 - 如果需要标注复用,可以自行维护视图复用池,在标注移出视野时调用
mapView.viewAnnotations.remove()回收视图,和原有复用逻辑兼容 - 所有原有CALayer相关的动画逻辑不需要做任何修改,可以直接沿用6版本的实现
内容的提问来源于stack exchange,提问作者Joshua Hart
相关产品推荐
相关产品推荐

