概述
对于自定义绘制, 官⽅为我们提供了三个 Modifier API,分别是drawWithContent、drawBehind 、drawWithCache。
- drawWithContent
drawWithContent 需要⼀个Reciever为 ContentDrawScope 类型的lambda,⽽这个ContentDrawScope 拓展了 DrawScope 的能⼒, 多了个 drawContentAPI。这个 API 是提供给开发者来控制绘制层级的。
fun Modifier.drawWithContent(
onDraw: ContentDrawScope.() -> Unit
)
interface ContentDrawScope : DrawScope {
/**
* Causes child drawing operations to run during the `onPaint`
lambda. */
fun drawContent()
}
- drawBehind
drawBehind,画在后面。具体画在谁后面呢,具体画在他所修饰的UI组件后面。
fun Modifier.drawBehind(
onDraw: DrawScope.() -> Unit
) = this.then(
DrawBackgroundModifier(
onDraw = onDraw, // onDraw 为我们定制的绘制控制逻辑
... )
)
private class DrawBackgroundModifier(
val onDraw: DrawScope.() -> Unit,
... ) : DrawModifier, InspectorValueInfo(inspectorInfo) {
override fun ContentDrawScope.draw() {
onDraw() // 先画我们定制的绘制控制逻辑
drawContent() // 后画UI组件本身
}
... }
@Preview
@Composable
fun DrawBehind() {
Box(
modifier = Modifier.fillMaxSize(), 6 contentAlignment = Alignment.Center
) {
Card(
shape = RoundedCornerShape(8.dp)
,modifier = Modifier
.size(100.dp)
.drawBehind {
drawCircle(Color(0xffe7614e), 18.dp.toPx() / 2, center = Offset(drawContext.size.width, 0f))
}
) {
Image(painter = painterResource(id = R.drawable.diana), contentDescription = "")
}
}
}
- drawWithCache
有些时候我们绘制⼀些⽐较复杂的UI效果时,不希望当 Recompose 发⽣时所有绘画所⽤的所有实例都重新构建⼀次 (类似Path),这可能会产⽣内存抖动。在Compose 中我们⼀般 能够想到使⽤ remember 进⾏缓存 ,然⽽我们所绘制的作⽤域是 DrawScope 并不是 Composable,所以⽆法使⽤ remember,那我们该怎么办呢?
drawWithCache 提供了这 个能⼒。
fun Modifier.drawWithCache(
onBuildDrawCache: CacheDrawScope.() -> DrawResult
)
class CacheDrawScope internal constructor() : Density {
...
fun onDrawBehind(block: DrawScope.() -> Unit): DrawResult
fun onDrawWithContent(block: ContentDrawScope.() -> Unit):
DrawResult
...
}
网友评论