如何在swift中使用MapKit旋转自定义userLocationAnnotationView图像?

时间:2016-09-15 10:03:45

标签: ios swift mapkit mkannotationview direction

我正试图找到一种方法,使用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))


}

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

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { 

var userLocationView :MKAnnotationView?

func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    print(newHeading.magneticHeading)
}

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

此时我无法向您提供完整的代码示例,但我希望我能给您一些指导。

首先,我认为你不一定要继承MKAnnotationView。您只需将UIImage分配给其image媒体资源即可。我认为除非你确实需要定制,否则会使事情变得更容易。

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

要旋转标题指示符,我会看到三个选项:

  1. 轮换MKAnnotationView' image属性
    • 方法:当标题更改时,创建UIImage的旋转副本并将其分配给image属性。 Example(未经测试)。
    • Con:不能轻易为旋转设置动画。
  2. 轮换MKAnnotationView本身
    • 方法:当标题发生变化时,请使用MKAnnotationView' s / UIView' transform属性。为其指定适当的CGAffineTransform
    • Pro:最简单
    • Con:还旋转细节/标注视图。如果您需要这些,这将不适合您。
  3. UIImage置于UIImageViewadd that one as a subviewMKAnnotationView
    • 方法:与2.类似,但使用UIImageView上的transform属性,而不是MKAnnotationView本身。这样就不会轮换标注视图。
    • 亲:应该运作良好。
    • Con:多做一点工作。
  4. 你还需要什么:

    • 将度数转换为弧度的函数。仿射变换需要弧度。
    • 如果您想为旋转设置动画(1除外),请将更改包含在transform 静态 {{3}中的UIView属性中方法。