如何使用MapKit快速旋转自定义userLocationAnnotationView图像?

iji*_*iji 3 direction mapkit mkannotationview ios swift

我正在尝试找到一种使用MapKit在地图上显示用户方向的方法。MapKit的本机方法总是旋转整个地图。由于用户位置也是MKAnnotationView,因此我决定创建一个特定的类来覆盖它并使用特定的图像(带有箭头)。

class UserLocationAnnotationView: MKAnnotationView {

override init(frame: CGRect) {
    super.init(frame: frame)
}

override init(annotation: MKAnnotation!, reuseIdentifier: String!) {

    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

    var frame = self.frame
    frame.size = CGSizeMake(130, 130)
    self.frame = frame
    self.backgroundColor = UIColor.clearColor()
    self.centerOffset = CGPointMake(-30, -50)

}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
override func drawRect(rect: CGRect) {
    // Drawing code
    UIImage(named: "userLocation.png")?.drawInRect(CGRectMake(65, 65, 65, 65))


}
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试找到一种在locationManager的didUpdateHeading函数中旋转该MKAnnotationView图像的方法。

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { 

var userLocationView :MKAnnotationView?

func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    print(newHeading.magneticHeading)
}
Run Code Online (Sandbox Code Playgroud)

newHeading.magneticHeading的打印有效并且非常准确。现在如何旋转我的自定义UserLocationAnnotationView?

谢谢你的帮助。

Art*_*hur 5

目前,我无法为您提供完整的代码示例,但我希望可以给您一些提示。

首先,我认为您不一定必须继承MKAnnotationView。您可以简单地将UIImage其分配给它的image属性。我认为这将使事情变得容易,除非您确实需要自定义。

现在,我假设您已成功将注释添加到地图并具有对它的引用。

要旋转航向指示器,我看到三个选项:

  1. Rotate MKAnnotationViewimage属性
    • 方法:标题更改时,创建的旋转副本并将其UIImage分配给image属性。示例(未经测试)。
    • 缺点:无法轻松地为旋转设置动画。
  2. 旋转MKAnnotationView本身
    • 方法:更改标题时,请使用MKAnnotationView's / UIView' transform属性。CGAffineTransform给它分配一个合适的。
    • 优点:最简单
    • 缺点:还旋转详细信息/标注视图。如果您需要这些,这将不是您的选择。
  3. UIImageUIImageView添加一个作为一个子视图MKAnnotationView
    • 方法:类似于2。但是直接使用transform属性而UIImageView不是MKAnnotationView自身。这样,标注视图不会旋转。
    • 优点:应该运作良好。
    • 缺点:还有点工作。

您还需要什么:

  • 将度数转换为弧度的功能。仿射变换需要弧度。
  • 如果您想为旋转动画(除1以外),请将更改包装到transform属性UIViewstatic animate方法中。