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

标签 ios swift mapkit mkannotationview direction

我正在尝试找到一种使用 MapKit 在 map 上显示用户方向的方法。 执行此操作的原生 MapKit 方法总是旋转整个 map 。 由于用户位置也是一个 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 ?

感谢您的帮助。

最佳答案

目前我无法为您提供完整的代码示例,但我希望我能为您提供一些指导。

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

现在,我假设您已成功将注释添加到 map 并获得了对它的引用。

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

  1. 旋转 MKAnnotationViewimage 属性:
    • 方法:当标题发生变化时,创建 UIImage 的旋转副本并将其分配给 image 属性。 Example(未测试)。
    • 缺点:无法轻松地设置旋转动画。
  2. 旋转 MKAnnotationView 本身:
    • 方法:当标题改变时,使用MKAnnotationView的/UIViewtransform属性。为其分配适当的 CGAffineTransform
    • 专业:最简单
    • 缺点:还会旋转细节/标注 View 。如果您需要这些,这将不是您的选择。
  3. UIImage 放入 UIImageView 并将 add that one as a subview 放入 MKAnnotationView:
    • 方法:与 2. 类似,但直接在 UIImageView 上使用 transform 属性,而不是在 MKAnnotationView 本身上使用。这样标注 View 就不会旋转。
    • 专业人士:应该运作良好。
    • 缺点:需要多做一些工作。

您还需要:

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

关于ios - 如何在 swift 中使用 MapKit 旋转自定义 userLocationAnnotationView 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508296/

相关文章:

ios - 电子邮件中的条件深层链接或 url

swift 2.0,Alamofire : Set cookies in HTTP Post Request

swift - 过滤数据 从vapor客户端获取

ios - 如何使用 mapkit 和 swift 在设定位置覆盖一个圆圈

swift - "Compiler error: Invalid library file"在 Debug > Location 中模拟位置 - CoreLocation 和 MapKit

iOS Swift 后台位置监控

ios - 如何在 UITableViewRowAction 中添加图像?

ios - SCNLevelOfDetails 委托(delegate)/通知

ios - 使用 MBXMapkit (Mapbox) 以用户位置为中心的 map

ios - 使 UIPageControl 在每个页面上停止