Learning Android Development
Code Simple Android Jetpack Compose Drawing App
Detect touch to draw on Canvas using Jetpack Compose
--
If you plan to learn Android, the most fun app to start is to make a simple drawing app. Instead of learning the conventional way of drawing, let’s learn using the latest Android Jetpack Compose to do so.
Pre-requisite of Setting Jetpack Compose
As Jetpack Compose is still in Alpha release, to use it, you need to download Android Studio 4.2 (Canary version) and do the setup as below
Drawing in Jetpack Compose
To have a drawing app, we just need three things
- A Canvas for one to draw onto
- The touch detection (touch down, and touch move)
- Drawing the path based on touch detection.
Setting up the Canvas
Unlike the conventional Android Development, it no longer uses layout. Hence we no longer need to build a custom view and have it drawn onto the Canvas.
Instead, we do have a Canvas Compose function.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) setContent {
Canvas(modifier = Modifier.fillMaxSize()) {
// Drawing happens here
}
}
}
Here we set up the Modifier
with fillMaxSize()
, so that it used up the entire space of the app.
Detection of touch
To detect touch, conventionally in Android, in the custom view, we override the onTouchEvent
function.
override fun onTouchEvent(event: MotionEvent?): Boolean {
when…