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

问题描述 投票:0回答:2

我对mapkit有点新意,但我想知道,我可以为地图上的每个引脚设置不同的图像。例如,字典中存在用户信息,而不是常规图像,必须有自己的图像。我应该如何为以下输出设置viewFor注释方法。

[{
email = "[email protected]";
id = jqvDgcBoV9Y4sx1BHCmir5k90dr1;
name = User1;
profileImageUrl = "<null>";
}, {
email = "[email protected]";
id = bqvDmcBoV9Y4sx1BqCmirnk90drz;
name = User2;
profileImageUrl = "https://firebasestorage.googleapis.com/v0/";
}, {
email = "[email protected]";
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

}
ios swift mapkit nsdictionary mkannotation
2个回答
1
投票

首先,让我说我认为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 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:)方法中提取出来并将其放在注释视图类中,以便更好地分工并避免视图控制器膨胀。

因此,例如,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中简单地注册这两个类:

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)) } } } 您可能想要考虑是否需要填充方面或类似的东西,但这里有一些其他的概念排列:https://stackoverflow.com/a/28513086/1271826。或者,或许更好,看看AlamofireImageKingfisher的调整大小例程。 但是带回家的信息是你应该把血腥的大小调整逻辑从viewForAnnotation中拉出来并进入它自己的例程/库。
  2. 你真的应该为用户位置使用出列逻辑。
  3. 注意,我只是做简单的URLSession.shared.dataTask而不寻找缓存等等。你显然可以在这里变得更复杂(例如缓存已调整大小的图像视图等)。
  4. 这不是什么大问题,但我觉得这个结构有点笨拙: guard !annotation.isKind(of: MKUserLocation.self) else { ... } 所以我简化了使用is测试。例如。: if annotation is MKUserLocation { ... } 这在很大程度上是相同的,但更直观一点。
  5. 请注意,上述例程与您的一样,使用调整大小的占位符图像作为注释视图的image属性。为了将来的读者,请允许我说这很重要,因为标准注释视图不能优雅地处理image大小的异步更改。您可以修改该类来执行此操作,或者更简单,就像我们在这里一样,使用标准大小的占位符图像。

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


1
投票

但我想知道,我可以为地图上的每个图钉设置不同的图像

当然。您需要创建自定义注释类型。您的自定义注释类型将在您将为其提供的实例属性中包含图像信息。这样,当你到达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属性,您将知道该怎么做。

© www.soinside.com 2019 - 2024. All rights reserved.