我可以为地图中的每个图钉分配不同的图像吗?

Can I assign different images to every pin in the map?

我对 mapkit 有点陌生,但我想知道,我可以为地图上的每个图钉设置不同的图像吗?例如,字典中有用户信息,而不是常规的 pin 图像必须是他们自己的图像。我应该如何为以下输出设置 viewFor 注释方法。

[{
email = "user1@gmail.com";
id = jqvDgcBoV9Y4sx1BHCmir5k90dr1;
name = User1;
profileImageUrl = "<null>";
}, {
email = "user2@gmail.com";
id = bqvDmcBoV9Y4sx1BqCmirnk90drz;
name = User2;
profileImageUrl = "https://firebasestorage.googleapis.com/v0/";
}, {
email = "user3@gmail.com";
id = axmDgcB5V9m4sx1nHC5ir5kn1dn3;
name = User3;
profileImageUrl = "https://firebasestorage.googleapis.com/v0/";
}]

顺便说一下,我有一个函数可以将 URL 转换为 UIImageView,但不是 UIImage,这是我的一大难题。

我现在的 viewForAnnotation 委托。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    var annotationView: MKAnnotationView?
    var annotationViewx: MKAnnotationView?
    let annotationIdentifier = "AnnotationIdentifier"

    guard !annotation.isKind(of: MKUserLocation.self) else {
        var annotationViewq: MKAnnotationView?
        annotationViewq = MKAnnotationView(annotation: annotation, reuseIdentifier: "userLocation")
        annotationViewq?.image = UIImage(named: "myLocation.png")


        let size = CGSize(width: 17, height: 17)
        UIGraphicsBeginImageContext(size)
        annotationViewq?.image!.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        annotationViewq?.image = resizedImage
        annotationViewq?.isEnabled = true
        annotationViewq?.isUserInteractionEnabled = true
        return annotationViewq

    }


    if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
        annotationView = dequeuedAnnotationView
        annotationView?.annotation = annotation
        annotationView?.canShowCallout = true
        annotationView?.image = UIImage(named: "emptyPhoto.png")

        let size = CGSize(width: 17, height: 17)
        UIGraphicsBeginImageContext(size)
        annotationView?.image!.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        annotationView?.image = resizedImage

        return annotationView
    }
        //This annotation not working. but not problem
        let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
        av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        annotationViewx?.canShowCallout = true
        annotationViewx?.image = UIImage(named: "trafficIcon.png")

        let size = CGSize(width: 17, height: 17)
        UIGraphicsBeginImageContext(size)
        annotationViewx?.image!.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        annotationViewx?.image = resizedImage
        annotationViewx = av


    return annotationViewx

}

but i wonder, can i set different images to every pin on the map

当然可以。您需要创建自定义注释类型。您的自定义注释类型将在您提供的实例 属性 中携带图像信息。这样,当你到达 mapView(_:viewFor:) 时,你就会知道这个注释需要什么图像并可以分配它。

示例:

class MyAnnotation : NSObject, MKAnnotation {
    dynamic var coordinate : CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    var imageName: String?

    init(location coord:CLLocationCoordinate2D) {
        self.coordinate = coord
        super.init()
    }
}

创建注释时,在将其附加到地图之前,还要分配给它的 imageName。现在地图调用委托请求图像视图,您可以阅读imageName 属性,您将知道该怎么做。

首先,让我说我认为 matt 已经抓住了问题的根源,即如果你有自己的图像的注释,你应该定义你自己的注释类型来捕获 URL图片,例如

class CustomAnnotation: NSObject, MKAnnotation {
    dynamic var coordinate: CLLocationCoordinate2D
    dynamic var title: String?
    dynamic var subtitle: String?

    var imageURL: URL?

    init(coordinate: CLLocationCoordinate2D, title: String? = nil, subtitle: String? = nil, imageURL: URL? = nil) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
        self.imageURL = imageURL

        super.init()
    }
}

添加注释时,请确保提供 URL,然后您就可以开始比赛了。我要指出的唯一一件事是您真的想跟踪哪个网络请求与哪个注释相关联(以便您可以在需要时取消它)。所以我会添加一个 URLSessionTask 属性 到注释视图 class:

class CustomAnnotationView: MKAnnotationView {
    weak var task: URLSessionTask?    // keep track of this in case we need to cancel it when the annotation view is re-used
}

老实说,我会把你所有复杂的配置代码都从mapView(_:viewFor:)方法中拉出来,放在注解视图classes中,这样可以更好地分工,避免view controller膨胀。

因此,例如,MKUserLocation 注释的自定义注释视图:

class CustomUserAnnotationView: MKAnnotationView {
    static let reuseIdentifier = Bundle.main.bundleIdentifier! + ".customUserAnnotationView"
    private let size = CGSize(width: 17, height: 17)

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        image = UIImage(named: "myLocation.png")?.resized(to: size)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

另一个用于 CustomAnnotation 注释 imageURL 属性,它将异步获取所需的图像:

class CustomAnnotationView: MKAnnotationView {
    static let reuseIdentifier = Bundle.main.bundleIdentifier! + ".customAnnotationView"

    private weak var task: URLSessionTask?
    private let size = CGSize(width: 17, height: 17)

    override var annotation: MKAnnotation? {
        didSet {
            if annotation === oldValue { return }

            task?.cancel()
            image = UIImage(named: "emptyPhoto.png")?.resized(to: size)
            updateImage(for: annotation)
        }
    }

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        canShowCallout = true
        rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        image = UIImage(named: "emptyPhoto.png")?.resized(to: size)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func updateImage(for annotation: MKAnnotation?) {
        guard let annotation = annotation as? CustomAnnotation, let url = annotation.imageURL else { return }

        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            guard let data = data,
                let image = UIImage(data: data)?.resized(to: self.size),
                error == nil else {
                    print(error ?? "Unknown error")
                    return
            }

            DispatchQueue.main.async {
                UIView.transition(with: self, duration: 0.2, options: .transitionCrossDissolve, animations: {
                    self.image = image
                }, completion: nil)
            }
        }
        task.resume()
        self.task = task
    }
}

然后,在 iOS 11 和更高版本中,我的视图控制器可以简单地在 viewDidLoad:

中注册这两个 classes
mapView.register(CustomUserAnnotationView.self, forAnnotationViewWithReuseIdentifier: CustomUserAnnotationView.reuseIdentifier)
mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: CustomAnnotationView.reuseIdentifier)

然后,mapView(_:viewFor:) 提炼成一个更简单的方法:

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let identifier: String

        switch annotation {
        case is MKUserLocation:   identifier = CustomUserAnnotationView.reuseIdentifier
        case is CustomAnnotation: identifier = CustomAnnotationView.reuseIdentifier
        default:                  return nil
        }

        return mapView.dequeueReusableAnnotationView(withIdentifier: identifier, for: annotation)
    }
}

请注意,我已尝试解决隐藏在您的 viewForAnnotation 方法中的一大堆其他问题,特别是:

  1. 您的图片调整逻辑 (a) 重复了几次; (b) 没有调用 UIGraphicsEndImageContext。所以,我建议把它去掉(例如在这个 UIImage 扩展中)并且不妨使用 UIGraphicsImageRenderer 来简化它:

    extension UIImage {
        func resized(to size: CGSize) -> UIImage {
            return UIGraphicsImageRenderer(size: size).image { _ in
                draw(in: CGRect(origin: .zero, size: size))
            }
        }
    }
    

    您可能想考虑是否需要纵横比填充或类似的东西,但这里有一些其他的想法排列:. Or, perhaps better, take a look at the resizing routines of AlamofireImage or Kingfisher

    但重要的是,您应该将血淋淋的调整大小逻辑从 viewForAnnotation 中拉出并放入它自己的 routine/library。

  2. 您确实也应该为用户位置使用出队逻辑。

  3. 注意,我只是在做简单的 URLSession.shared.dataTask,没有寻找缓存等。您显然可以在这里变得更复杂(例如缓存调整大小的图像视图等)。

  4. 没什么大不了的,但我发现这个结构有点笨拙:

    guard !annotation.isKind(of: MKUserLocation.self) else { ... }
    

    所以我简化了使用 is 测试。例如:

    if annotation is MKUserLocation { ... }
    

    大致相同,但更加直观。

  5. 请注意,上面的例程和您的例程一样,对注释视图的 image 属性 使用了调整大小的占位符图像。为了未来的读者,让我说这很重要,因为标准注释视图不能优雅地处理 image 大小的异步更改。您可以修改 class 来执行此操作,或者更简单,就像我们在这里使用的那样,使用标准大小的占位符图像。

请注意,请参阅 prior revision of this answer iOS 10.x 及更早版本。