方法:iOS MapKit 动画图像标记/注释

HowTo: iOS MapKit animated image marker / annotation

我有一系列图像要用作动画,我想将此动画应用到特定注释。

如何更改 MapKit 默认注释图像以及如何使其动画化?

要制作自定义图像动画图像标记注释:

  • 在资源中:添加所需的动画 X 序列图像:frame_1.png 至 frame_X.png
  • 在代码中:使用 MKMapViewDelegte 扩展您的视图控制器,如下所示:

class MyViewController: MKMapViewDelegate

在情节提要中:

  1. 选择您的 MapKit 视图
  2. 转到实用程序框架并选择 连接检查器
  3. 将委托元素与您的 控制器。

现在您的视图控制器可以从 MapView 获得回调。

在代码中: 添加以下代码以覆盖 marker/annotation 设置回调

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        if !(annotation is MKPointAnnotation) {
            return nil
        }

        let reuseId = "test"

        anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if anView == nil {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView!.image = UIImage(named:"frame_1")
            anView!.canShowCallout = true


           Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(Changeimage), userInfo: nil, repeats: true)

        }
        else {
            anView!.annotation = annotation
        }

        return anView
    }

    func Changeimage()
    {
        if count == 8
        {
            count=0
        }
        else
        {
            anView!.image = UIImage(named:"frame_\(count+1)")
            anView!.canShowCallout = true
            count=count+1
        }
    }

如果不需要动画,只需从代码中删除 Timer 行即可。