compose jetpack canvas简单入门
2021-03-17 本文已影响0人
随心随弈走
原文出自这里
https://medium.com/mobile-app-development-publication/code-simple-android-jetpack-compose-drawing-app-886d1146ad20
文章标题为:使用简单代码在 Android Jetpack Compose 中开发绘图应用
文章有不少转载,由于版本的更新,它不能正常工作了,所以在这里更正一下
我所使用的环境为
compose_version = '1.0.0-beta01'
classpath "com.android.tools.build:gradle:7.0.0-alpha09"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.30"
distributionUrl=https://services.gradle.org/distributions/gradle-6.8.2-bin.zip
代码如下:
class MainActivity : ComponentActivity() {
private val action: MutableState<Pair<Float, Float>?> = mutableStateOf(null)
private val path = Path()
private val collectList = mutableListOf<Pair<Float, Float>>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Canvas(
modifier = Modifier
.fillMaxSize()
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
action.value = Pair(it.x, it.y)
path.moveTo(it.x, it.y)
}
MotionEvent.ACTION_MOVE -> {
action.value = Pair(it.x, it.y)
path.lineTo(it.x, it.y)
}
else -> false
}
true
}) {
action.value?.let {
collectList.add(it)
drawPath(
path = path,
color = Color.Green,
alpha = 1f,
style = Stroke(10f)
)
}
}
}
}
}