Last active
September 2, 2021 12:47
-
-
Save sergei-lapin/b3320bc85823a5078daa7fe6ca3f1633 to your computer and use it in GitHub Desktop.
A simple rotate gesture detector with API simillar to android.view.ScaleGestureDetector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RotateGestureDetector(private val onRotateListener: OnRotateListener) { | |
| val rotationDeltaDegrees: Float | |
| get() { | |
| val diffRadians = atan2(prevDiffY, prevDiffX) - atan2(currDiffY, currDiffX) | |
| return Math.toDegrees(diffRadians.toDouble()).toFloat() | |
| } | |
| var focusX = 0f | |
| private set | |
| var focusY = 0f | |
| private set | |
| private var currDiffX = 0f | |
| private var currDiffY = 0f | |
| private var prevDiffX = 0f | |
| private var prevDiffY = 0f | |
| private var isInProgress = false | |
| fun onTouchEvent(event: MotionEvent): Boolean { | |
| val action = event.actionMasked | |
| val count = event.pointerCount | |
| val isStreamComplete = | |
| action == MotionEvent.ACTION_UP || | |
| action == MotionEvent.ACTION_CANCEL || | |
| action == MotionEvent.ACTION_POINTER_UP && count < 2 | |
| if (isStreamComplete) { | |
| if (isInProgress) onRotateListener.onRotateEnd(this) | |
| isInProgress = false | |
| return true | |
| } | |
| if (count < 2) return false | |
| focusX = (event.getX(0) + event.getX(1)) / 2f | |
| focusY = (event.getY(0) + event.getY(1)) / 2f | |
| if (action == MotionEvent.ACTION_POINTER_DOWN && !isInProgress) { | |
| onRotateListener.onRotateBegin(this) | |
| calculateCurrDiff(event) | |
| isInProgress = true | |
| return true | |
| } | |
| prevDiffX = currDiffX | |
| prevDiffY = currDiffY | |
| calculateCurrDiff(event) | |
| onRotateListener.onRotate(this) | |
| return true | |
| } | |
| private fun calculateCurrDiff(event: MotionEvent) { | |
| currDiffX = event.getX(1) - event.getX(0) | |
| currDiffY = event.getY(1) - event.getY(0) | |
| } | |
| interface OnRotateListener { | |
| fun onRotateBegin(detector: RotateGestureDetector): Boolean | |
| fun onRotate(detector: RotateGestureDetector): Boolean | |
| fun onRotateEnd(detector: RotateGestureDetector) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment