菜鸟教程小白 发表于 2022-12-11 19:33:46

ios - MapKit 中 MKMarkerAnnotationView 的彩色图像


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

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

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

<p>谁能帮我解决这个问题?</p>

<p>这是我的完整代码:</p>

<pre><code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {
    if annotation is MKUserLocation {
      return nil
    }

    let identifier = &#34;PinAnnotationIdentifier&#34;

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

    pinView?.annotation = annotation
    pinView?.clusteringIdentifier = &#34;clusterId&#34;
    pinView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)


    pinView?.canShowCallout = false
    pinView?.glyphImage = UIImage(named: &#34;image&#34;)


    return pinView
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>当你打电话时</p>
<pre><code>pinView?.glyphImage = UIImage(named: &#34;image&#34;)
</code></pre>
<p><code>pinView</code> 调用</p>
<pre><code>glyphImage?.withRenderingMode(.alwaysTemplate)
</code></pre>
<p>这提供了一种解决问题的简单方法:只需重写 <code>withRenderingMode</code>:</p>
<pre><code>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) -&gt; UIImage {
      // both return statements work:
      return self
      // return super.withRenderingMode(.alwaysOriginal)
    }

}
</code></pre>
<p>现在你可以使用</p>
<pre><code>pinView?.glyphImage = OriginalUIImage(named: &#34;image&#34;)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - MapKit 中 MKMarkerAnnotationView 的彩色图像,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48092900/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48092900/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - MapKit 中 MKMarkerAnnotationView 的彩色图像