UIRotationGestureRecognizer可以直角拍摄

时间:2017-08-10 18:19:12

标签: ios swift math uiview rotation

我试图让这种旋转机制以直角拍摄,例如当用户接近(85到95​​度)时,它会自动捕捉到90度,直到他离开85度或95度。

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 > -95 && degrees < -85 {

    }
    else if degrees > -185 && degrees < -175 {

    }
    else if degrees > -275 && degrees < -265 {

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

}

2 个答案:

答案 0 :(得分:0)

数学与您正在进行的检查并不相同(度数变量为:-180 ... 0 ... 180 - &gt; -180 ... 0等)。

另一个问题是sender.rotation是累积的,这意味着它会在你旋转时不断增加或减去rad。

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

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

    print("rotation", sender.rotation, degrees, rad)

    switch rad {
    case 1.48353...1.65806 :
        print("do things")
    case 3.05433...3.22886 :
        print("do things")
    case 4.62512...4.79966 :
        print("do things")
    case 0...0.0872665 :
        print("this is check one of 2")
    case 6.19592...6.28319 :
        print("this is check two of 2")
    default:
        print("do other things")
    }

编辑:https://developer.apple.com/documentation/uikit/uirotationgesturerecognizer/1624337-rotation

答案 1 :(得分:0)

易于移植的Objective-c

if (DISTANCE(rotationValue, round(rotationValue/(π/2.0))*(π/2.0)) < 0.05) {
    rotationValue = round(rotationValue/(π/2.0))*(π/2.0);//90º snapped
}

可选地使用以下宏:

#define π 3.14159265358979323846264338327950288 
#define DISTANCE(__valueOne, __valueTwo) ((((__valueOne)-(__valueTwo))>=0)?((__valueOne)-(__valueTwo)):((__valueTwo)-(__valueOne)))