Counterpart of onTouchEvent for Jetpack Compose and transform gesture with specific number of pointers

Overview

Jetpack Compose Gestures

Counterpart of onTouchEvent for Jetpack Compose and transform gesture with specific number of pointers

gestures.mp4

Modifier.pointerMotionEvents

Creates a modifier for processing pointer motion input within the region of the modified element.

After AwaitPointerEventScope.awaitFirstDown returns a PointerInputChange followed by onDown at first pointer contact. Moving any pointer invokes AwaitPointerEventScope.awaitPointerEvent then onMove is called. When last pointer is up onUp is called.

To prevent other pointer functions that call awaitFirstDown or awaitPointerEvent (scroll, swipe, detect functions) call PointerInputChange.consume() in onDown, and call PointerInputChange.consume() in onMove block.

fun Modifier.pointerMotionEvents(
    vararg keys: Any?,
    onDown: (PointerInputChange) -> Unit = {},
    onMove: (PointerInputChange) -> Unit = {},
    onUp: (PointerInputChange) -> Unit = {},
    delayAfterDownInMillis: Long = 0L
) = this.then(
    Modifier.pointerInput(keys) {
        detectMotionEvents(onDown, onMove, onUp, delayAfterDownInMillis)
    }
)

pointerMotionEventList returns list of pointers in onMove

fun Modifier.pointerMotionEventList(
    key1: Any? = Unit,
    onDown: (PointerInputChange) -> Unit = {},
    onMove: (List<PointerInputChange>) -> Unit = {},
    onUp: (PointerInputChange) -> Unit = {},
    delayAfterDownInMillis: Long = 0L
) 
  • delayAfterDownInMillis parameter invokes Coroutines delay between onDown, and onMove. There is a delay about 20ms between in View's onTouchEvent first touch and move, similar delay might be required with Compose too, especially when drawing to Canvas which misses very fast events, Delaying move behavior might be required to detect whether is touch is in required region of Composable at first pointer contact.

PointerInputChange down and move events should be consumed if you need to prevent other gestures like scroll or other pointerInputs to not intercept your gesture

 Modifier.pointerMotionEvents(
    onDown = {
        // When down is consumed
        it.consume()
    },
    onMove = {
        // Consuming move prevents scroll other events to not get this move event
        it.consume()
    },
    delayAfterDownInMillis = 20
)

You can refer this answer for details.

Modifier.detectTransformGesturesAndChanges

A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the user can use rotation, panning and zoom gestures. onGesture will be called when any of the rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and pan as an offset in pixels. Each of these changes is a difference between the previous call and the current gesture. This will consume all position changes after touch slop has been reached. onGesture will also provide centroid of all the pointers that are down.

After gesture started when last pointer is up onGestureEnd is triggered. pointerList returns info about pointers that are available to this gesture

Usage

Modifier.pointerInput(Unit) {
    detectTransformGesturesAndChanges(
        onGesture = { gestureCentroid: Offset,
                      gesturePan: Offset,
                      gestureZoom: Float,
                      gestureRotate: Float,
                      pointerList: List<PointerInputChange> ->

        },
        onGestureEnd = {
            transformDetailText = "GESTURE END"
        }
    )
}

Modifier.detectPointerTransformGestures

Transform gesture as detectTransformGestures except with gestureEnd callback, returns number of pointers that are down and checks for requisite and number of pointers before continuing transform gestures. when requisite is not met gesture is on hold and ends when last pointer is up. This might be useful in scenarios like not panning when pointer number is higher than 1, or scenarios require specific conditions to be met

Modifier
    .pointerInput(Unit) {
        detectPointerTransformGestures(
            numberOfPointers = 1,
            requisite = PointerRequisite.GreaterThan,
            onGesture = { gestureCentroid: Offset,
                          gesturePan: Offset,
                          gestureZoom: Float,
                          gestureRotate: Float,
                          numberOfPointers: Int ->

            },
            onGestureEnd = {
                transformDetailText = "GESTURE END"
            }
        )
    }

Gesture Tutorial

If you need more detailed tutorial about Jetpack Compose gestures check this tutorial

Gradle Setup

To get a Git project into your build:

  • Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:
allprojects {
  repositories {
      ...
      maven { url 'https://jitpack.io' }
  }
}
  • Step 2. Add the dependency
dependencies {
  implementation 'com.github.SmartToolFactory:Compose-Extended-Gestures:Tag'
}
You might also like...
πŸ›’ Mercado Libre App Clone using modern Android development with Hilt, Coroutines, Jetpack (Room, ViewModel), and Jetpack Compose based on MVVM architecture.
πŸ›’ Mercado Libre App Clone using modern Android development with Hilt, Coroutines, Jetpack (Room, ViewModel), and Jetpack Compose based on MVVM architecture.

Meli Clone πŸ›’ Mercado Libre App Clone using modern Android development with Hilt, Coroutines, Jetpack (Room, ViewModel), and Jetpack Compose based on

Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.

Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.

FirestoreCleanArchitectureApp is an app built with Kotlin and Firestore that displays data in real-time using the MVVM Architecture Pattern. For the UI it uses Jetpack Compose,  Android's modern toolkit for building native UI.
FirestoreCleanArchitectureApp is an app built with Kotlin and Firestore that displays data in real-time using the MVVM Architecture Pattern. For the UI it uses Jetpack Compose, Android's modern toolkit for building native UI.

FirestoreCleanArchitectureApp FirestoreCleanArchitectureApp is an app built with Kotlin and Cloud Firestore that displays data in real-time using Andr

Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Accounting-App - An Android app built with Kotlin, Material, Jetpack Compose, Hilt, Room, Coroutines, Data-Store, MVVM-Clean Architecture and JUnit tests
Clean Android multi-module offline-first scalable app in 2022. Including Jetpack Compose, MVI, Kotlin coroutines/Flow, Kotlin serialization, Hilt and Room.

Android Kotlin starter project - 2022 edition Android starter project, described precisely in this article. Purpose To show good practices using Kotli

Build with Jetpack Compose & all modern techniques and architecture of android app development
Build with Jetpack Compose & all modern techniques and architecture of android app development

IMDB Movie App Build with Jetpack Compose & all modern techniques and architecture of android app development ScreenShots πŸ›  Built With πŸ›  Kotlin - Fi

Affogato is a multipurpose library for Android, Jetpack Compose and Kotlin.
Affogato is a multipurpose library for Android, Jetpack Compose and Kotlin.

Affogato Affogato is a multipurpose library for Jetpack Compose, Android and Kotlin. Core-ktx Core-ktx is a Kotlin library that provides a set of Kotl

Math Your Brain is a math game built using Jetpack Compose and Modern MVVM Architecture
Math Your Brain is a math game built using Jetpack Compose and Modern MVVM Architecture

Math Your Brain is a math game built using Jetpack Compose and Modern MVVM Architecture. I built this so that programmers learning Jetpack Compose Can use this repository as a learning material for Jetpack Compose.

Releases(2.1.0)
  • 2.1.0(Sep 14, 2022)

  • 2.0.0(Jul 3, 2022)

    This version adds Modifier.touchDelegate that changes touch area of a Composable without changing its scale or dimensions. Tranform gestures are now contain mainPointer and number of pointers that are down and have option to consume PointerInputChanges. consume flag is true by default as default transform gestures but you can change it in some situations to selectively pass events to other gestures such as drag or scroll which are used by Pagers or LazyLists.

    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(May 20, 2022)

    remove partial consumes, add requireUnconsumed flag

    • As of Compose 1.2.0-beta01 partial consumes are deprecated, so removing them in favor of consume()

    • Adding option requireUnconsumed flag for other pointerInputs to receive awaitFirstDown(requireUnconsumed =false) event even if we consume it. This flag is default flag for awaitFirstDown, now it can be passable to default function

    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(May 10, 2022)

    This version add new transform gestures with onGestureEnd callback that notifies last pointer is up and return number of pointers that are down or list of PointerInputChange which contains details about current pointers.

    Source code(tar.gz)
    Source code(zip)
Owner
Smart Tool Factory
πŸš€ Building colorful shiny things with Jetpack Compose from Thrace fueled with 🍺 , β˜•οΈ and 🀘
Smart Tool Factory
Kafka Connect JSLT Single Message Transform

This is an implementation of the Kafka Connect SMT interface to offer transformation capabilities using the Schibsted JSLT library.

willhaben 2 May 25, 2022
A basic library that enables easy composition of gesture sequence recognition on a view

GestureSequence A basic library that enables easy composition of gesture sequence recognition on a view. Basic API looks like: // Perform action() whe

Paul Klauser 8 Nov 2, 2022
A TODO list app with location reminders that remind the user to do something when the user is at a specific location

Project Title Location Reminder Getting Started A TODO list app with location reminders that remind the user to do something when the user is at a spe

Raghav Saboo 0 Dec 5, 2021
A specific format represent file directory in Json

CascadeJson.kt A specific format represent file directory in Json Provide a function for convert to map or json string in Kotlin Usage Download zip fi

CWKSC 1 Feb 22, 2022
A Simple Android library to get the number of words and give you the time it will take you to finish an article/story.

MinRead A Simple Android library to get the number of words and give you the time it will take you to finish an article/story. Prerequisite Androidx K

Nwokocha wisdom maduabuchi 36 Nov 17, 2021
πŸͺ„ This is an animation library with an increasing number of TextViews

CountNumberEvent ?? This is an animation library with an increasing number of TextViews Demo Setup Add it in your root build.gradle at the end of repo

박상선 5 Feb 17, 2022
Send Whatsapp Message Without Saving Mobile Number

Send Whatsapp Message Without Saving Mobile Number In this project i created the

THANGADURAI SELVARAJ 2 Apr 22, 2022
FizzBuzzKotlin - A function fizzBuzz to generate a list of string based on the input number

FizzBuzzKotlin write a function fizzBuzz to generate a list of string based on t

gson 0 Feb 12, 2022
This project aims to provide a solution for finding the right product for a given EAN (European Article Number)

This project aims to provide a solution for finding the right product for a given EAN (European Article Number)

MJ 1 Apr 18, 2022