设计师经常通过将“我们的”自定义主题中的现有颜色放在另一个应用了 Alpha 的顶部来构建自定义颜色。 如何在不应用多个背景的情况下计算结果颜色? 类似的东西
val background = MaterialTheme.colors.MyDanger.copy(alpha = 0.12f) + MaterialTheme.colors.CustomTint16
Plus 没有为颜色定义,因为它不是可交换的,但是有没有办法在代码中将一种颜色放在另一种颜色之上并仅应用结果?
val result = color1.compositeOver(color2)
这就是我一直在寻找的
示例1:
// Ratio value has to be 0.5 to achive even mix.
//The 3rd argument is ratio(the proportion while blending the colors). eg.
//If you want 30% of color1 & 70% of color2, then do ColorUtils.blendARGB(***, ***, 0.3F);
int resultColor = androidx.core.graphics.ColorUtils.blendARGB(color1, color2, 0.5F);
示例2:
public static int mixColor(int color1, int color2, float ratio) {
final float inverse = 1 - ratio;
float a = (color1 >>> 24) * inverse + (color2 >>> 24) * ratio;
float r = ((color1 >> 16) & 0xFF) * inverse + ((color2 >> 16) & 0xFF) * ratio;
float g = ((color1 >> 8) & 0xFF) * inverse + ((color2 >> 8) & 0xFF) * ratio;
float b = (color1 & 0xFF) * inverse + (color2 & 0xFF) * ratio;
return ((int) a << 24) | ((int) r << 16) | ((int) g << 8) | (int) b;
}
最后,我在
ColorUtils.blendARGB
之上实现了这个实现。
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.graphics.ColorUtils
fun Color.blend(topColor: Color, ratio: Float = 0.5f): Color {
if (ratio == 0f) return this
if (ratio == 1f) return topColor
val intColor = ColorUtils.blendARGB(toArgb(), topColor.toArgb(), ratio)
return Color(intColor)
}
和用法(在背景上添加一点额外的绿色):
modifier = Modifier
.background(MaterialTheme.colorScheme.background.blend(Green200))
实际上,
.compositeOver()
做同样的事情,但方式很奇怪:它是extraColor的扩展。你应该写extraColor.compositeOver(mainColor)
。如果您需要有条件地添加额外颜色,则没有用。
此外,
compositeOver
不支持比例(ratio
在我建议的扩展中)。
但最后,
extraColor.compositeOver(mainColor)
上的代码与mainColor.blend(extraColor, 0.5f)
相同。