如何在地图框 3.6 中旋转汽车标记图像?



我想根据路线方向旋转标记图像。我使用地图框SDK实现了地图。坐标和方向通过网络服务获取。 我尝试了imageForMarker,但它不起作用。实施如下

func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
let img = imageRotatedByDegrees(oldImage: UIImage(named: "car")!, deg: CGFloat(self.bearing))
return MGLAnnotationImage(image: img, reuseIdentifier: "car")
}
func imageRotatedByDegrees(oldImage: UIImage, deg degrees: CGFloat) -> 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
}

尝试使用自定义重用标识符,如下所示:

func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
let annotation = annotation as! CustomMapAnnotation
var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: annotation.id)
if annotationImage == nil {
var image = UIImage(named: "taxi")!
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
}

看起来正确的方法是将MGLSymbolStyleLayer与您的注释一起使用,而不是直接添加注释并使用mapview委托方法: https://www.mapbox.com/ios-sdk/api/3.6.2/Classes/MGLSymbolStyleLayer.html#/c:objc(cs(MGLSymbolStyleLayer(py(iconRotate

您可以使用一个 iconRotate 属性,该属性采用度数。

这很不幸,因为我的用例有几个相同的图像但不同的标题,所以我必须为每个图像添加一个图层。

最新更新