我正在尝试找到一种使用 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 并获得了对它的引用。
要旋转航向指示器,我看到三个选项:
- 旋转
MKAnnotationView
的image
属性:- 方法:当标题发生变化时,创建
UIImage
的旋转副本并将其分配给image
属性。 Example(未测试)。 - 缺点:无法轻松地设置旋转动画。
- 方法:当标题发生变化时,创建
- 旋转
MKAnnotationView
本身:- 方法:当标题改变时,使用
MKAnnotationView
的/UIView
的transform
属性。为其分配适当的CGAffineTransform
。 - 专业:最简单
- 缺点:还会旋转细节/标注 View 。如果您需要这些,这将不是您的选择。
- 方法:当标题改变时,使用
- 将
UIImage
放入UIImageView
并将 add that one as a subview 放入MKAnnotationView
:- 方法:与 2. 类似,但直接在
UIImageView
上使用transform
属性,而不是在MKAnnotationView
本身上使用。这样标注 View 就不会旋转。 - 专业人士:应该运作良好。
- 缺点:需要多做一些工作。
- 方法:与 2. 类似,但直接在
您还需要:
- 将度数转换为弧度的函数。仿射变换需要弧度。
- 如果您想为旋转设置动画(1 除外),请将更改包装到
UIView
的 staticanimate
中的transform
属性方法。
关于ios - 如何在 swift 中使用 MapKit 旋转自定义 userLocationAnnotationView 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508296/