ios - MapKit 中 MKMarkerAnnotationView 的彩色图像

标签 ios mapkit mkmapview mapkitannotation

我正在为 iOS 构建一个应用程序,允许用户基于位置存储图像。 现在我想为此使用 iOS 中最新的 AnnotationView (MKMarkerAnnotationView),因为它提供了自动集群。

我的问题是,这个类需要一个 glyphTintColor,如果没有提供,它被设置为 UIColor().red。 iOS 使用此颜色为整个图像着色。之后图像只有这种颜色。 我尝试将 glyphTintColor 设置为 nil 但这会导致图像变成红色。我还尝试将其设置为 UIColor(red:1.00, green:1.00, blue:1.00, alpha:0.0) 但之后图像消失了,您只能看到标记本身。

我希望标记以其原始颜色而不是单一颜色显示图像。

谁能帮我解决这个问题?

这是我的完整代码:

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

    let identifier = "PinAnnotationIdentifier"

    var pinView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)

    pinView?.annotation = annotation
    pinView?.clusteringIdentifier = "clusterId"
    pinView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)


    pinView?.canShowCallout = false
    pinView?.glyphImage = UIImage(named: "image")


    return pinView
}

最佳答案

当你打电话时

pinView?.glyphImage = UIImage(named: "image")

pinView 调用

glyphImage?.withRenderingMode(.alwaysTemplate)

这提供了一种解决问题的简单方法:只需重写 withRenderingMode:

import UIKit

class OriginalUIImage: UIImage {

    convenience init?(named name: String) {
        guard let image = UIImage(named: name),
              nil != image.cgImage else {
                    return nil
        }
        self.init(cgImage: image.cgImage!)
    }

    override func withRenderingMode(_ renderingMode: UIImage.RenderingMode) -> UIImage {
        // both return statements work:
        return self
        // return super.withRenderingMode(.alwaysOriginal)
    }

}

现在你可以使用

pinView?.glyphImage = OriginalUIImage(named: "image")

关于ios - MapKit 中 MKMarkerAnnotationView 的彩色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48092900/

相关文章:

ios - 快速在 map 上添加 MKTileOverlay

ios - Objective-c 如何对 textField 进行验证

iphone - 如何在 ios 6 的 map 上绘制路线?

iOS 8 - 动画显示导航栏和状态栏无法正常工作

ios - 确定纬度/经度点是否在 Mapview 中的 MKPolygon 中?

iphone - 在后台加载 MKMapView 并从中创建 UIImage (iPhone 和 iPad)

iphone - 放大/缩小时 MKAnnotationView 错误更改了图钉图像

ios - 如何在swift中通过单元格解析json纬度和经度

iOS Firebase - 获取照片网址时出现问题(未解析的标识符)

ios - 重载iOS Swift中的通用函数