Sur*_*Sau 12 android android-jetpack-compose
我尝试使用 BlendMode.SRC_IN 在 PNG 图像(具有透明背景)顶部添加覆盖颜色,但背景变为黑色,而不是设置的背景颜色,就像也屏蔽了背景像素一样。
@Composable
fun Icon(
fraction: Float,
image: ImageAsset,
defaultColor: Color = Color(0xFFEEEEEE),
progressColor: Color = Color(0xFF888888),
size: Dp = image.width.dp
) {
Box(modifier = Modifier.size(size = size)) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawImage(
image = image,
dstSize = IntSize(
width = size.toIntPx(),
height = size.toIntPx()
),
colorFilter = ColorFilter.tint(
color = defaultColor
),
blendMode = BlendMode.Src
)
drawIntoCanvas {
val paint = Paint().apply {
color = progressColor
blendMode = BlendMode.SrcIn
}
it.restore()
it.drawRect(
rect = Rect(
offset = Offset.Zero,
size = Size(
width = size.toPx() * fraction,
height = size.toPx()
)
),
paint = paint
)
it.save()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Icon()
这是当我在一个类似的顶部排列多个时的样子Screen(color = Color.WHITE)
,
Surface(color = Color.White) {
Row {
listOf(
R.drawable.anemo,
R.drawable.cryo,
R.drawable.dendro,
R.drawable.electro,
R.drawable.geo,
R.drawable.hydro,
R.drawable.pyro
).forEachIndexed { index, imageRes ->
val from = 100f/7 * index
val to = 100f/7 * (index + 1)
val fraction = when {
progress > to -> 1f
progress > from -> (progress - from)/(to - from)
else -> 0f
}
Icon(
fraction = fraction,
image = imageResource(id = imageRes),
size = 50.dp
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么吗?
这是我正在尝试这个的Github 存储库。
就我而言,我可以通过添加如下修改器来解决应该是透明像素的黑色像素的问题graphicsLayer
:
Box(
modifier = Modifier.fillMaxSize()
) {
Canvas(modifier = Modifier
.fillMaxSize()
.graphicsLayer(alpha = 0.99f)
) {
drawRect(
color = Color.Black,
size = size,
blendMode = BlendMode.Xor
)
drawCircle(
color = Color.Black,
radius = 300f,
blendMode = BlendMode.Xor
)
}
}
Run Code Online (Sandbox Code Playgroud)
没有修饰符:
带修饰符:
我从这里得到了这个想法:https://gist.github.com/nadewad/14f04c788aea43bd6d31d94cd8100ab5(请注意,drawLayer
已重命名为graphicsLayer
.
.graphicsLayer(alpha = 0.99f)
是一个有效的解决方法,但是,它改变了内容的 alpha,这是不必要的。
要将绘图重定向到离屏渲染目标,android.graphics.Canvas#saveLayer(android.graphics.RectF, android.graphics.Paint)
可以使用一个简单的修饰符,如下所示:
fun Modifier.drawOffscreen(): Modifier = this.drawWithContent {
with(drawContext.canvas.nativeCanvas) {
val checkPoint = saveLayer(null, null)
drawContent()
restoreToCount(checkPoint)
}
}
Run Code Online (Sandbox Code Playgroud)
restoreToCount
并且在调用之前内容将被绘制到屏幕外。
归档时间: |
|
查看次数: |
5736 次 |
最近记录: |