是否可以将图像添加到MapBox中的自定义MGLAnnotationView(iOS,Swift)

时间:2017-03-24 12:47:29

标签: ios swift xcode mapbox

Mapbox提供了有关自定义注释图像和自定义注释视图的方便文档:

https://www.mapbox.com/ios-sdk/examples/annotation-views/ https://www.mapbox.com/ios-sdk/examples/marker-image/

然而,似乎无法将这些想法组合在一起并自定义注释视图的图像。基本上我希望做的是有一张照片的注释(用户选择),它也有一个可以在点击时动画的边框。

有没有人遇到这个限制?

2 个答案:

答案 0 :(得分:4)

MGLAnnotationView继承自UIView,因此您可能用于向视图添加图片的大部分技术也适用于此处。

一种简单的方法是将UIImageView添加为自定义MGLAnnotationView子类中的子视图:

class CustomImageAnnotationView: MGLAnnotationView {
    var imageView: UIImageView!

    required init(reuseIdentifier: String?, image: UIImage) {
        super.init(reuseIdentifier: reuseIdentifier)

        self.imageView = UIImageView(image: image)
        self.addSubview(self.imageView)
        self.frame = self.imageView.frame
    }

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

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
}

然后在mapView:viewForAnnotation:中使用该子类:

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    guard annotation is MGLPointAnnotation else {
        return nil
    }

    let imageName = "someImageThatYouHaveAddedToYourAppBundle"

    // Use the image name as the reuse identifier for its view.
    let reuseIdentifier = imageName

    // For better performance, always try to reuse existing annotations.
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)

    // If there’s no reusable annotation view available, initialize a new one.
    if annotationView == nil {
        annotationView = CustomImageAnnotationView(reuseIdentifier: reuseIdentifier, image: UIImage(named: imageName)!)
    }

    return annotationView
}

答案 1 :(得分:0)

func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
  var annotationImage : MGLAnnotationImage? = nil
  annotationImage = MGLAnnotationImage(image:UIImage(named: "imageyouwanttoset", reuseIdentifier: annotation.title)
  return annotationImage
}