【问题标题】:How to rotate custom userLocationAnnotationView image using MapKit in swift?如何在 swift 中使用 MapKit 旋转自定义 userLocationAnnotationView 图像?
【发布时间】:2016-09-15 10:03:45
【问题描述】:

我正在尝试找到一种使用 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 ?

感谢您的帮助。

【问题讨论】:

    标签: ios swift mapkit mkannotationview direction


    【解决方案1】:

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

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

    现在,我假设您已成功将注释添加到地图并对其进行了引用。

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

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

    你还需要什么:

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

    【讨论】:

    • 非常感谢@Arthur!即使您没有提供任何代码,您的回答也是准确的,并且通过您的不同方法,我找到了使其工作的方法。我决定使用第二种方法,因为我不需要 userAnnotationView 的任何标注视图。最后一个关于使用 UIView 的动画方法的建议也是一个巨大的帮助。再次感谢您
    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多