微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UIPanGestureRecognizer 旋转 mapView

如何解决UIPanGestureRecognizer 旋转 mapView

我有一种使用 UIPanGestureRecognizer 平移地图的方法,但是它不能正确旋转(我希望能够进行圆周运动,使相机沿圆圈移动),这里有更好的方法吗?

@objc func panMap (sender: UIPanGestureRecognizer) {
        if sender.state == .began {
            print("began")
        } else if sender.state == .changed {
            // rotating map camera
            let position = sender.translation(in: mapView)
            let newDirection = mapView.camera.heading.advanced(by: (Double(position.x) + Double(position.y)))
            let newCamera: MKMapCamera = MKMapCamera(lookingAtCenter: mapView.camera.centerCoordinate,fromdistance: mapView.camera.altitude,pitch: mapView.camera.pitch,heading: newDirection)
            mapView.setCamera(newCamera,animated: false)

          // Eugene Dudnyk's solution to help fix logic error when appending distance
          sender.setTranslation(.zero,in: mapView) 

        } else if sender.state == .ended {
            print("end")
        }
    }

解决方法

问题是平移手势识别器的 translation 相对于平移开始时的位置累积,但您将其解释为自上次状态更改以来的累积,并始终添加到相机角度。

如果用户将手指移到 afa.x = 160,然后将手指移回,afa.x 会从 160 度变为 150 度,但是您将附加到角度 150 / 30 = 5 degrees,其中角度具有为否定,- 10 / 30 degrees 代替。

试试这个,也许它会让事情变得更好:

@objc func panMap (sender: UIPanGestureRecognizer) {
    if sender.state == .began {
        print("began")
    } else if sender.state == .changed {
        // rotating map camera
        let translation = sender.translation(in: mapView)
        let location = sender.location(in: mapView)
        let bounds = mapView.bounds
        let vector1 = CGVector(dx: location.x - bounds.midX,dy: location.y - bounds.midY)
        let vector2 = CGVector(dx: vector1.dx + translation.x,dy: vector1.dy + translation.y)
        let angle1 = atan2(vector1.dx,vector1.dy)
        let angle2 = atan2(vector2.dx,vector2.dy)
        mapView.camera.heading += (angle2 - angle1) * 180.0 / Double.pi
    } else if sender.state == .ended {
        print("end")
    }

    sender.setTranslation(.zero,in: mapView)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。