菜鸟教程小白 发表于 2022-12-11 18:34:34

ios - 如何在 Mapbox 3.6 中旋转汽车标记图像?


                                            <p><p>我想根据路线方向旋转标记图像。我已经使用 Map box SDK 实现了 map 。坐标和方向是通过网络服务获取的。
我尝试了 imageForMarker 但它没有用。实现如下</p>

<pre><code>func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -&gt; MGLAnnotationImage? {

    let img = imageRotatedByDegrees(oldImage: UIImage(named: &#34;car&#34;)!, deg: CGFloat(self.bearing))

    return MGLAnnotationImage(image: img, reuseIdentifier: &#34;car&#34;)
}
func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -&gt; UIImage
{
    let size = oldImage.size

    UIGraphicsBeginImageContext(size)

    let bitmap: CGContext = UIGraphicsGetCurrentContext()!
    //Move the origin to the middle of the image so we will rotate and scale around the center.
    bitmap.translateBy(x: size.width / 2, y: size.height / 2)
    //Rotate the image context
    bitmap.rotate(by: (degrees * CGFloat(Double.pi / 180)))
    //Now, draw the rotated/scaled image into the context
    bitmap.scaleBy(x: 1.0, y: -1.0)

    let origin = CGPoint(x: -size.width / 2, y: -size.width / 2)

    bitmap.draw(oldImage.cgImage!, in: CGRect(origin: origin, size: size))

    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>尝试使用自定义重用标识符,如下所示:</p>

<pre><code>func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -&gt; MGLAnnotationImage? {
    let annotation = annotation as! CustomMapAnnotation

    var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: annotation.id)

    if annotationImage == nil {
      var image = UIImage(named: &#34;taxi&#34;)!

      if let heading = annotation.heading {
            image = image.imageRotatedByDegrees(degrees: heading)
      }
      image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height/2, right: 0))

      annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: annotation.id)
    }

    return annotationImage
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 Mapbox 3.6 中旋转汽车标记图像?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45907301/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45907301/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 Mapbox 3.6 中旋转汽车标记图像?