Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- override fun onTouchEvent(event: MotionEvent): Boolean {
- // abuse-proof multitouch code - minimize the use of event type
- val lastUp: Boolean = when (event.action and MotionEvent.ACTION_MASK) {
- MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> true
- else -> false
- }
- val pointerCount = event.pointerCount
- // collect all points
- var points: MutableList<Array<Float>> = mutableListOf()
- for (i in 0 until pointerCount) {
- val id = event.getPointerId(i) // stable value
- val index = event.findPointerIndex(id) // temporary value
- val x = event.getX(index)
- val y = event.getY(index)
- points.add(arrayOf(x, y))
- }
- // find nearest path
- val getDist = { a: MyPath, b: Array<Float> -> (a.lastX - b[0]).pow(2) + (a.lastY - b[1]).pow(2) }
- var nearestDist: MutableMap<Int, Float> = mutableMapOf()
- var nearestKey: MutableMap<Int, Int> = mutableMapOf()
- //TODO: convert above two to MutableList
- for (i in 0 until pointerCount) {
- val smallest = mPaths.minByOrNull { getDist(it.value, points[i]) } ?: break
- nearestDist[i] = getDist(smallest.value, points[i])
- nearestKey[i] = smallest.key
- }
- val sortedPointsIndex: List<Int> = (0 until pointerCount).toList().sortedBy { nearestDist[it] }
- // iterate through points and update paths
- mPathsStatus.forEach { mPathsStatus[it.key] = 0 } // 0: new point not mapped, 1: new point mapped
- for (i in sortedPointsIndex) {
- val x = points[i][0]
- val y = points[i][1]
- if (mPathsStatus[nearestKey[i]] != 0) { // new point
- mTouchPoints ++
- // assign new unused index
- var newIndex = mTouchPoints-1
- for (i in 0 until mTouchPoints-1) {
- if (mPaths[i] == null) {
- newIndex = i
- break
- }
- }
- // update path
- mPaths[newIndex] = MyPath()
- mPaths[newIndex]!!.moveTo(x, y)
- mPathsStatus[newIndex] = 1
- } else if (!lastUp) { // nearest point
- mPaths[nearestKey[i]]!!.lineTo(x, y)
- mPathsStatus[nearestKey[i]!!] = 1
- }
- }
- // migrate inactive paths to prevPaths
- val notUpdated = mPathsStatus.filter { it.value == 0 }
- notUpdated.forEach {
- mTouchPoints --
- mPrevPaths.add(mPaths[it.key]!!)
- mPaths.remove(it.key)
- mPathsStatus.remove(it.key)
- }
- invalidate() // force draw new
- return true
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement