2016-09-15 65 views
1

我试图找到一种方法来显示使用MapKit的用户在地图上的方向。 原生的MapKit方式总是会旋转整个地图。 由于用户位置也是一个MKAnnotationView,我决定创建一个特定的类来覆盖它并使用特定的图像(带有箭头)。如何在swift中使用MapKit自定义userLocationAnnotationView图像?

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 FUNC旋转该MKAnnotationView图像。

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { 

var userLocationView :MKAnnotationView? 

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

newHeading.magneticHeading的版画作品,它相当准确。 现在如何旋转我的自定义UserLocationAnnotationView?

感谢您的帮助。

回答

2

我现在还不能给你完整的代码示例,但我希望我能给你一些指导。

首先,我认为你不一定要继承MKAnnotationView。您可以简单地将您的UIImage分配给它的image属性。我认为这会让事情变得更容易,除非你需要定制。

现在,我假设你已经成功地将注释添加到地图并且有一个对它的引用。

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

  1. 旋转MKAnnotationViewimage财产
    • 方法:当标题更改,创建UIImage的旋转副本和将其分配给image属性。 Example(未测试)。精灵:无法轻松地旋转动画。
  2. 旋转MKAnnotationView本身
    • 方法:当标题改变,使用MKAnnotationView的/ UIViewtransform财产。为其分配合适的CGAffineTransform。结果:同时旋转细节/标注视图。
    • 赞成:最简单
    • Con:也旋转细节/标注视图。如果你需要这些,这不会成为你的选择。
  3. UIImageUIImageViewadd that one as a subviewMKAnnotationView
    • 方法:以2类似,但在MKAnnotationView本身的UIImageView使用transform财产不直接。这样标注视图不会旋转。
    • 临:应该很好。 Con:稍微多一点工作。

什么,你还需要:

  • 的函数从度转换为弧度。仿射变换需要弧度。
  • 如果要为动画旋转(除1之外),请将属性中的更改包装为UIView静态animate方法。
+0

非常感谢@Arthur!即使你没有给出任何代码,你的答案是确切的,并用你的不同方法,我发现我的方式使其工作。我决定使用第二种方法,因为我不需要userAnnotationView的任何标注视图。另外最后一条关于使用UIView动画方法的建议非常有帮助。再次感谢你 – matthioo

相关问题