如何计算在Android上用alpha通道叠加两个颜色整数的结果



我在 Android 上有两种颜色,其中 alpha 通道表示为整数,我需要让这些颜色的结果颜色相互叠加(就好像我有两个半透明视图一样(。

我已经尝试使用ColorUtils.blendARGB的变化,但这并不完全是我所需要的。

我可以很容易地计算出这样的东西:

/**
 * Takes receiver as top color and attempts to overlay it over param color.
 * Result is basically [ColorUtils.blendARGB] but in overlay mode instead of blend mode.
 */
infix fun Int.overlay(bottomColor: Int): Int {
    val ratio = 1 - ((Color.alpha(this) / 255f) * (Color.alpha(bottomColor) / 255f))
    return ColorUtils.blendARGB(ColorUtils.setAlphaComponent(this, 255), ColorUtils.setAlphaComponent(bottomColor, 255), ratio)
}

然而,很明显,如果两种颜色都有阿尔法通道,这将不起作用,因为它会完全删除阿尔法。

如何同时保留两种叠加颜色的 alpha 通道?

我认为这将混合尊重其阿尔法的颜色。

@ColorInt infix fun @receiver:ColorInt Int.overlay(@ColorInt bottomColor: Int): Int {
    val topAlpha = Color.alpha(this)
    val bottomAlpha = Color.alpha(bottomColor)
    val alphaSum = bottomAlpha + topAlpha
    return Color.argb(
        Math.min(255, alphaSum),
        (Color.red(bottomColor) * bottomAlpha + Color.red(this) * topAlpha) / alphaSum,
        (Color.green(bottomColor) * bottomAlpha + Color.green(this) * topAlpha) / alphaSum,
        (Color.blue(bottomColor) * bottomAlpha + Color.blue(this) * topAlpha) / alphaSum
    )
}

最新更新