如何在swift中使用MapKit自定义userLocationAnnotationView图像?
我试图find一种方法来显示使用MapKit的用户在地图上的方向。 本地MapKit的方式,总是旋转整个地图。 由于用户的位置也是一个MKAnnotationView,我决定创build一个特定的类来覆盖它,并使用特定的图像(带箭头)。
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)) }
现在我试图find一种方法来在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
属性。 我认为这会让事情变得简单,除非你需要定制。
现在,我假设你已经成功地将注释添加到地图并且有一个参考。
要旋转标题指示符,我看到三个选项:
- 旋转
MKAnnotationView
的image
属性 :- 方法:当标题改变时,创build
UIImage
的旋转副本并将其分配给image
属性。 示例 (未testing)。 - 骗局:不能轻松地旋转animation。
- 方法:当标题改变时,创build
- 旋转
MKAnnotationView
本身 :- 方法:当标题改变时,使用
MKAnnotationView
的/UIView
的transform
属性。 为其分配一个合适的CGAffineTransform
。 - Pro:最简单
- Con:同时旋转细节/标注视图。 如果你需要这些,这不会是你的select。
- 方法:当标题改变时,使用
- 把
UIImage
放到一个UIImageView
然后把它作为子视图添加到MKAnnotationView
:- 方法:类似于2,但直接使用
UIImageView
上的transform
属性而不是在MKAnnotationView
本身。 这样标注视图不会旋转。 - 亲:应该好好工作。
- Con:多一点工作。
- 方法:类似于2,但直接使用
你还需要什么:
- 从度数转换为弧度的函数。 仿射变换需要弧度。
- 如果要为animation旋转(除了1),请将更改包装到
UIView
的静态animate
方法中的transform
属性中。