菜鸟教程小白 发表于 2022-12-11 18:29:31

ios - UI 旋转手势识别器捕捉直角


                                            <p><p>我正在尝试使用这种旋转机制来捕捉直角,例如当用户接近(85 到 95 度)时,它会自动捕捉到 90 度,直到他离开 85 或 95 度。</p>

<pre><code>var lastRotation = CGFloat()
func rotateAction(sender:UIRotationGestureRecognizer){


    let currentTransform = sender.view?.transform
    let rotation = 0.0 - (lastRotation - sender.rotation)
    let newTransform = currentTransform!.rotated(by: rotation)

    let radians = atan2f(Float(sender.view!.transform.b), Float(sender.view!.transform.a))
    let degrees = radians * (180 / .pi)

    sender.view?.transform = newTransform
    lastRotation = sender.rotation
    if sender.state == .ended {
      lastRotation = 0.0;
    }

    // The if statement works correctly when reaching the angles
    if degrees &gt; -95 &amp;&amp; degrees &lt; -85 {

    }
    else if degrees &gt; -185 &amp;&amp; degrees &lt; -175 {

    }
    else if degrees &gt; -275 &amp;&amp; degrees &lt; -265 {

    }
    else if degrees &gt; -5 &amp;&amp; degrees &lt; 5 {
      // So I tried this but it does not seem right, it always pushed it away from angle 0
      lastRotation = CGFloat(0.0 - radians)
    }

}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>数学与您正在进行的检查不符(度数变量为:-180...0...180 -> -180...0 等)。 </p>

<p>另一个问题是 sender.rotation 是累积的,这意味着它会在您旋转时不断增加或减少弧度。</p>

<p>一旦其他数学被修复,我会建议类似于以下内容来检查“快照”。</p>

<pre><code>    let rad = fabs(sender.rotation.truncatingRemainder(dividingBy: 2 * CGFloat.pi))

    print(&#34;rotation&#34;, sender.rotation, degrees, rad)

    switch rad {
    case 1.48353...1.65806 :
      print(&#34;do things&#34;)
    case 3.05433...3.22886 :
      print(&#34;do things&#34;)
    case 4.62512...4.79966 :
      print(&#34;do things&#34;)
    case 0...0.0872665 :
      print(&#34;this is check one of 2&#34;)
    case 6.19592...6.28319 :
      print(&#34;this is check two of 2&#34;)
    default:
      print(&#34;do other things&#34;)
    }
</code></pre>

<p>编辑:<a href="https://developer.apple.com/documentation/uikit/uirotationgesturerecognizer/1624337-rotation" rel="noreferrer noopener nofollow">https://developer.apple.com/documentation/uikit/uirotationgesturerecognizer/1624337-rotation</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UI 旋转手势识别器捕捉直角,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45620889/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45620889/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UI 旋转手势识别器捕捉直角