如何在Swift中的动态角度开关上使线条弯曲?

How to make line curved on dynamic angle switch in Swift?

我正在创建一个迷宫,我需要移动在 panGestureRecognized 上创建的线以适应我手指的运动:

代码:

@IBAction func panGestureRecognized(_ sender: UIPanGestureRecognizer) {
       // print("started")
        
        if let scene = self.scene, let view = sender.view {
            
            let location = sender.location(in: view)
            let translation = sender.translation(in: view)
            let velocity = sender.velocity(in: view)

                do {
                            audioPlayer = try AVAudioPlayer(contentsOf: beginSound)
                            audioPlayer.play()
                       } catch {
                          // couldn't load file :(
                       }
                self.view.layer.addSublayer(lineShape)
            }
            else if sender.state == .changed {
//                scene.panChanged(location: cameraLocation, translation: cameraTranslation, velocity: cameraVelocity)
                let linePath = UIBezierPath()
                linePath.move(to: CGPoint(x: 368.0, y: 299.5))
                    linePath.addLine(to: location)

                    lineShape.path = linePath.cgPath
            }
            else if sender.state == .ended {
//                scene.panEnded(location: cameraLocation, translation: cameraTranslation, velocity: cameraVelocity)
//                sender.setTranslation(CGPoint(x: 0, y:0), in: view)
                lineShape.path = nil
                lineShape.removeFromSuperlayer()
                
                do {
                    
                            audioPlayer = try AVAudioPlayer(contentsOf: failedSound)
                            audioPlayer.play()
                       } catch {
                          // couldn't load file :(
                       }
                
                print("ended")
            }
        }
    }

如何向左旋转线条?

如果您想创建一条跟随用户手指移动的路径,那么您需要跟踪位置并使用这些位置构建您的路径。需要添加一个新的 属性 例如

private var gestureLocations: [CGPoint] = []

然后在更改时您需要附加点并重新绘制

        else if sender.state == .changed {
            gestureLocations.append(location)
            let linePath = UIBezierPath()
            linePath.move(to: CGPoint(x: 368.0, y: 299.5))
            gestureLocations.forEach { linePath.addLine(to: [=11=]) }
            lineShape.path = linePath.cgPath
        }

应该清除路径时结束清除点

            lineShape.path = nil
            lineShape.removeFromSuperlayer()
            gestureLocations = []

但这只会绘制自由形式的路径。查看您要实现的目标(在迷宫中画一条线),您应该将这些点捕捉到迷宫中的一些兴趣点。这样用户就不能穿墙画画。但这是另一个问题,对于 Whosebug 来说太宽泛了。