2016-06-10 5 views
2

Apple지도 응용 프로그램을 만들고 MKCircle 및 MKPolyline을 사용하여 위치 매핑을 처리했습니다.Swift를 사용하여 특히 AnnotationView를 회전하십시오.

그리고지도보기에서 사용자 정의 주석 업데이트 방법 위에

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? 
{} 

을 사용했다.

어노테이션이 특정 시점에 도달하는 동안 이미지를 회전시킬 수 있습니까?

필자의 요구 사항은 Los Angeles와 New York에서 마침내 Mexico City로 시작하여 3 곳으로 이동 했으므로 뉴욕에 도달하는 주석은 주석 이미지를 회전시키고 싶습니다. 가능한 한 메모를 제안 해주십시오.

자세한 내용은 아래의 코딩 부분을 참조하십시오.

// 
    // ViewController.swift 
    // RouteMap 
    // 
    // Created by Suthan M. 
    // Copyright © 2016 suthan.nimalan.m All rights reserved. 
    // 

    import UIKit 
    import MapKit 

    extension Double { 
    /** Converts the specified value in degrees into radians. */ 

    func degrees() -> CGFloat { 
     return CGFloat(self) * CGFloat(M_PI/180.0) 
    } 
} 

class ViewController: UIViewController,MKMapViewDelegate { 

    @IBOutlet var mkMapView: MKMapView! 

    var flightpathPolyline: MKGeodesicPolyline! 
    var planeAnnotation: MKPointAnnotation! 
    var planeAnnotationPosition = 0 
    var planeDirection: CLLocationDirection! 
    var testValue: MKMapPoint! 
    var testCount: Int! 
    var radiusInSomething : CLLocationDistance = 10000000.0 
    var circle:MKCircle! 

    override func viewDidAppear(animated: Bool) { 

     let location = CLLocationCoordinate2D(
      latitude: 33.9424955, 
      longitude: -118.4080684 
     ) 

     self.mkMapView.setRegion(MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 95, longitudeDelta: 95)), animated: true) 

     let LAX = CLLocation(latitude: 33.9424955, longitude: -118.4080684) 
     let JFK = CLLocation(latitude: 40.6397511, longitude: -73.7789256) 
     let WAS = CLLocation(latitude: 19.432608, longitude: -99.133209) 
     let mexicoCityLoc = CLLocationCoordinate2D(latitude: 19.4284700, longitude: -99.1276600) 

     mkMapView.addOverlay(MKCircle(centerCoordinate: mexicoCityLoc, 
      radius: radiusInSomething * MKMetersPerMapPointAtLatitude(mexicoCityLoc.latitude))) 

     var coordinates = [LAX.coordinate, JFK.coordinate, WAS.coordinate] 
     flightpathPolyline = MKGeodesicPolyline(coordinates: &coordinates, count: 3) 

     mkMapView.addOverlay(flightpathPolyline) 

     let coordin = CLLocationCoordinate2D(latitude: 19.4284700, longitude: -99.1276600) 
     circle = MKCircle(centerCoordinate: coordin, radius: 2000) 
     mkMapView.addOverlay(circle) 

     let annotation = MKPointAnnotation() 
     annotation.title = NSLocalizedString("Plane", comment: "Plane marker") 
     mkMapView.addAnnotation(annotation) 

     self.planeAnnotation = annotation 
     self.updatePlanePosition() 

    } 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     // Work with MKMapview 

     self.planeDirection = 360.0 
     testCount = 0 

     mkMapView.delegate = self 
     mkMapView.mapType = MKMapType.Standard 
     mkMapView.showsUserLocation = true 

    } 


    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { 


     if overlay is MKPolyline { 

      let renderer = MKPolylineRenderer(overlay: overlay) 
      renderer.lineWidth = 3.0 
      renderer.alpha = 0.5 
      renderer.strokeColor = UIColor.blueColor() 

      return renderer 

     }else if overlay is MKCircle { 

      let circleRenderer = MKCircleRenderer(overlay: overlay) 
      circleRenderer.fillColor = UIColor.blueColor().colorWithAlphaComponent(0.1) 
      circleRenderer.strokeColor = UIColor.blueColor() 
      circleRenderer.lineWidth = 1 

      return circleRenderer 

     } 

     return MKOverlayRenderer() 
    } 

    func updatePlanePosition() { 

     let step = 5 
     guard planeAnnotationPosition + step < flightpathPolyline.pointCount 
      else { return } 

     let points = flightpathPolyline.points() 
     self.planeAnnotationPosition += step 
     let nextMapPoint = points[planeAnnotationPosition] 

     self.planeAnnotation.coordinate = MKCoordinateForMapPoint(nextMapPoint) 

     let previousMapPoint = points[planeAnnotationPosition] 
     planeAnnotationPosition += step 

     self.planeDirection = directionBetweenPoints(previousMapPoint, nextMapPoint) 

     // set turn point of plane 

     if(testValue.x == 79197107.0566392){ 

      testCount = 1 
      planeDirection = 360.0 

      self .mapView(mkMapView, viewForAnnotation: planeAnnotation) 
     } 

     performSelector("updatePlanePosition", withObject: nil, afterDelay: 0.03) 

    } 

    private func directionBetweenPoints(sourcePoint: MKMapPoint, _ destinationPoint: MKMapPoint) -> CLLocationDirection { 

     //print(sourcePoint) 

     //MKMapPoint(x: 74074213.8054451, y: 105154930.159039) 
     //MKMapPoint(x: 74074213.8054451, y: 105154930.159039) 

     testValue = sourcePoint 

     let x = destinationPoint.x - sourcePoint.x 
     let y = destinationPoint.y - sourcePoint.y 

     return radiansToDegrees(atan2(y, x)) % 360 + 90 
    } 

    private func radiansToDegrees(radians: Double) -> Double { 
     return radians * 180/M_PI 
    } 

    private func degreesToRadians(degrees: Double) -> Double { 
     return degrees * M_PI/180 
    } 

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 

     let planeIdentifier = "Plane" 

     let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(planeIdentifier) 
      ?? MKAnnotationView(annotation: annotation, reuseIdentifier: planeIdentifier) 

     annotationView.image = UIImage(named: "pointer") 

     if(testCount == 1){ 

      let angle = CGFloat(self.degreesToRadians(self.planeDirection)) 
      annotationView.transform = CGAffineTransformRotate(mapView.transform, angle) 

     } 
     else{ 

      let angle = CGFloat(degreesToRadians(planeDirection)) 
      annotationView.transform = CGAffineTransformRotate(mapView.transform, angle) 

     } 

     return annotationView 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

Current Snap

감사합니다.

답변

1

내 경우에는 대상으로 향하고 있습니다. 그래서 저는 프로젝트에서 주석보기가 아닌 이미지를 좋아하는 것과 같았습니다.

// viewForAnnotation 방법

annotationView.image = UIImage(named: "pointer")?.imageRotatedByDegrees(CGFloat(angle), flip: false) 

은 내가 확장자를 추가했다. https://ruigomes.me/blog/how-to-rotate-an-uiimage-using-swift/

extension UIImage { 
     public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage { 
     //  let radiansToDegrees: (CGFloat) -> CGFloat = { 
    //   return $0 * (180.0/CGFloat(M_PI)) 
    //  } 

    let degreesToRadians: (CGFloat) -> CGFloat = { 
     return $0/180.0 * CGFloat(M_PI) 
    } 

    // calculate the size of the rotated view's containing box for our drawing space 
    let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size)) 
    let t = CGAffineTransformMakeRotation(degreesToRadians(degrees)); 
    rotatedViewBox.transform = t 
    let rotatedSize = rotatedViewBox.frame.size 

    // Create the bitmap context 
    UIGraphicsBeginImageContext(rotatedSize) 
    let bitmap = UIGraphicsGetCurrentContext() 

    // Move the origin to the middle of the image so we will rotate and scale around the center. 
    CGContextTranslateCTM(bitmap, rotatedSize.width/2.0, rotatedSize.height/2.0); 

    // // Rotate the image context 
    CGContextRotateCTM(bitmap, degreesToRadians(degrees)); 

    // Now, draw the rotated/scaled image into the context 
    var yFlip: CGFloat 

    if (flip) { 
     yFlip = CGFloat(-1.0) 
    } else { 
     yFlip = CGFloat(1.0) 
    } 

    CGContextScaleCTM(bitmap, yFlip, -1.0) 
    CGContextDrawImage(bitmap, CGRectMake(-size.width/2, -size.height/2, size.width, size.height), CGImage) 

    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    return newImage 
    } 
    } 
이미 내 코드 흐름에서 수행 이미지 먹으 렴을 회전 잘 작동 코드의 흐름을 제안한 것처럼
+0

,하지만 내 시나리오 나 좌표가 "뉴욕"에 도달하는 동안 이미지를 회전하려면, 나는의 포인트를 찾을 수 있습니다 위치는 특정 지점의 주석에 도달하면서 회전하려고하지만 이미지는 업데이트되지 않습니다. 자세한 정보는 아래의 메소드를 참조하십시오. - func mapView (mapView : MKMapView, viewForAnnotation annotation : MKAnnotation) -> MKAnnotationView? {} –

관련 문제