从URL下载并将其设置为GMSMarker后,如何解决闪烁的图像?

时间:2019-05-22 05:11:19

标签: swift google-maps google-maps-markers

这是我到目前为止所做的。当我调用函数应用图像时,视图中的所有标记均已设置其图像,但是当我缩小地图并检查其他标记时会出现问题,它们的图像会一直闪烁并且不会停止。我也希望我的图像是圆形的,但它们会一直变成六边形。 Here is the gif showing the problem.

func showCurrentLocationWithOnlineMarkers() {
    guard let locationObj = locationManager.location else {
        return
    }
    viwMaps.delegate = self
    let coord = locationObj.coordinate
    userLat = coord.latitude
    userLng = coord.longitude
    let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: userLat, longitude: userLng, zoom: Float(17.0))
    viwMaps.isMyLocationEnabled = true
    viwMaps.settings.myLocationButton = true
    self.viwMaps.animate(to: camera)
    for data in arrGetDriverModal{
            let driver_lat = CLLocationDegrees(data.driver_lat ?? "")
            let driver_long = CLLocationDegrees(data.driver_long ?? "")
            let location = CLLocationCoordinate2D(latitude: driver_lat!, longitude: driver_long!)
            let marker = GMSMarker()
            marker.position = location
            marker.userData = data
        marker.map = self.viwMaps
            let imageURL = URL(string: API.imgbaseURL+data.driver_image!)
                self.applyImage(from: imageURL!, to: marker)
    }

}

func applyImage(from url: URL, to marker: GMSMarker) {
    let imageView = UIImageView(image: #imageLiteral(resourceName: "marker"))
    imageView.frame = CGRect.init(x: 0, y: 0, width: 44, height: 44)
    DispatchQueue.global(qos: .background).async {
        guard let data = try? Data(contentsOf: url),
            let image = UIImage(data: data)
            else { return }

        DispatchQueue.main.async {
            imageView.image = image
            imageView.layer.cornerRadius = 22
            imageView.clipsToBounds = true
            imageView.layer.masksToBounds = true
            marker.iconView = imageView
        }
    }
}

1 个答案:

答案 0 :(得分:0)

制造商有点像可重复使用的单元,因此将图像保存到缓存可以提高性能。为此,翠鸟是一个很好的图书馆。安装并导入后,您可以使用这种情况;

func applyImage(from url: URL, to marker: GMSMarker) {
    let imageView = UIImage()
    imageView.frame = CGRect.init(x: 0, y: 0, width: 44, height: 44)

    let identifier =  "\(a specific name for each of your markers, could be coordinates or adress)"
    let url = URL(string: "your url")!
            let resource = ImageResource(downloadURL: url, cacheKey: identifier)
            imageView.kf.setImage(with: resource, placeholder: UIImage(named: 
          "placeholderIfYouHave.png")! )
    }
}