gpt4 book ai didi

android - Jetpack Compose Canvas drawText 颜色混合?

转载 作者:行者123 更新时间:2023-12-05 03:16:18 33 4
gpt4 key购买 nike

假设我在下面的 compose 中有以下代码。

背景洋红色圆圈,顶部带有默认黑色文本。

enter image description here

我想将圆圈上方的文本颜色混合为白色。

Canvas(
modifier = Modifier.size(256.dp),
onDraw = {
drawCircle(
color = Color.Magenta,
radius = 50f,
center = Offset(
x = size.width / 2,
y = size.height / 2),
)
val textSize = textMeasurer.measure(text = AnnotatedString("A"))
drawText(
textMeasurer = textMeasurer,
text = "A",
style = TextStyle(
color = Color.Black,
fontSize = 14.sp
),
topLeft = Offset(
x = size.width / 2 - 100f - (textSize.size.width / 2),
y = size.height / 2 - (textSize.size.height / 2)
)
)
drawText(
textMeasurer = textMeasurer,
text = "B",
style = TextStyle(
color = Color.Black,
fontSize = 14.sp
),
topLeft = Offset(
x = size.width / 2 - (textSize.size.width / 2),
y = size.height / 2 - (textSize.size.height / 2)
)
)
}
)

我已经尝试在许多不同的配置中在 cirle 上使用 BlendMode,但我无法使其工作。而且 drawText 没有我能看到的混合模式。

有没有一种简单的方法可以实现混合使圆圈上方的文字变白?

最佳答案

您要么需要设置要使用小于 1f 的混合模式的 Composable 的 alpha,要么使用要在其中绘制源和目标的层。降低 alpha 会在幕后添加层,这两者基本相同。

Jetpack Compose Applying PorterDuffMode to Image

How to clip or cut a Composable?

fun DrawScope.drawWithLayer(block: DrawScope.() -> Unit) {
with(drawContext.canvas.nativeCanvas) {
val checkPoint = saveLayer(null, null)
block()
restoreToCount(checkPoint)
}
}

由于 drawText 没有 blendMode 参数,我们需要将其绘制为目标,还添加了动画以通过 BlendMode 演示颜色变化。

enter image description here

@Composable
private fun BlendModeSample() {

val textMeasurer = rememberTextMeasurer()

val infiniteTransition = rememberInfiniteTransition()


val offset by infiniteTransition.animateFloat(
initialValue = -1f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 3000),
repeatMode = RepeatMode.Reverse
)
)
Canvas(
modifier = Modifier.size(256.dp),
onDraw = {

val textSize = textMeasurer.measure(text = AnnotatedString("A"))
drawText(
textMeasurer = textMeasurer,
text = "A",
style = TextStyle(
color = Color.Black,
fontSize = 14.sp
),
topLeft = Offset(
x = size.width / 2 - 100f - (textSize.size.width / 2),
y = size.height / 2 - (textSize.size.height / 2)
)
)


drawWithLayer {

// Destination
drawText(
textMeasurer = textMeasurer,
text = "B",
style = TextStyle(
color = Color.Black,
fontSize = 14.sp
),
topLeft = Offset(
x = size.width / 2 - (textSize.size.width / 2),
y = size.height / 2 - (textSize.size.height / 2) + offset * 100f
),

)

// Source
drawCircle(
color = Color.Magenta,
radius = 50f,
center = Offset(
x = size.width / 2,
y = size.height / 2
),
blendMode = BlendMode.SrcOut
)
}


}
)
}

您还可以查看使用混合模式构建评分栏。

Jetpack Compose: How to create a rating bar?

关于android - Jetpack Compose Canvas drawText 颜色混合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74723358/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com