8

使用简单代码在 Android Jetpack Compose 中开发绘图应用

 3 years ago
source link: https://www.infoq.cn/article/W9tdH01cJQYrrGuSC8Jy
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用 Jetpack Compose 触控功能在 Canvas 上画出图形。

如果大家有意学习 Android,不妨先从妙趣横生的绘图应用起步。在今天的文章中,我们将共同了解如何使用最新 Android Jetpack Compose 开发一款绘图应用。

7jmmiem.gif!mobile

设置 Jetpack Compose 的先决条件

目前 Jetpack Compose 仍处于 Alpha 测试阶段,因此大家必须下载 Android Studio 4.2(Canary 版)并完成以下设置才能使用。

在 Jetpack Compose 中绘图

绘图应用的开发流程非常简单,只需要三步:

  1. Canvas 绘图画布

  2. 触控检测(按压与触控移动)

  3. 根据触控检测绘制路径

设置 Canvas

与传统 Android 开发有所不同,这一次我们不再使用布局。因此,我们不需要构建自定义视图并将其绘制到 Canvas 之上。

override fun onCreate(savedInstanceState: Bundle?) {    super.onCreate(savedInstanceState)    setContent {         Canvas(modifier = Modifier.fillMaxSize()) {            // Drawing happens here        }    }}

复制代码

在这里,我们只需要通过 fillMaxSize() 设置 Modifier,确保其占用应用程序中的整个空间。

触控检测

要检测触控,我们通常需要在 Android 中的自定义视图内覆盖 onTouchEvent 函数。

override fun onTouchEvent(event: MotionEvent?): Boolean {    when (event?.action) {        MotionEvent.ACTION_DOWN -> { }        MotionEvent.ACTION_MOVE -> { }        MotionEvent.ACTION_UP -> { }        else -> return false    }    invalidate()    return true}

复制代码

在 Jetpack Compose 当中,我们使用 pointerInteropFilter 修饰符以检测触摸操作。

Canvas(modifier = Modifier        .fillMaxSize()        .pointerInteropFilter {            when (it.action) {                MotionEvent.ACTION_DOWN -> { }                MotionEvent.ACTION_MOVE -> { }                MotionEvent.ACTION_UP -> { }                else -> false            }            true        })

复制代码


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK