You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Compose自定义组件禁用态适配:API<29下灰度+0.8f透明度实现方案

兼容API<29的Jetpack Compose组件禁用态实现方案

针对API 29以下版本无法使用BlendMode.Saturation的问题,可通过以下两种方案实现组件转为灰度且透明度0.8f的禁用态:

方案一:ColorFilter灰度实现(全版本兼容)

利用ColorMatrix将内容饱和度置0实现灰度效果,结合graphicsLayer设置透明度,覆盖所有Compose支持的API版本:

Surface(
    modifier = modifier.graphicsLayer { alpha = 0.8f }
) {
    // 避免内容颜色因父级alpha被二次淡化
    CompositionLocalProvider(LocalContentColor provides LocalContentColor.current.copy(alpha = 1f)) {
        Box(
            modifier = Modifier.drawWithCache {
                val grayFilter = ColorFilter.colorMatrix(
                    ColorMatrix().apply { setToSaturation(0f) }
                )
                onDrawWithContent {
                    drawContent(colorFilter = grayFilter)
                }
            }
        ) {
            // 此处放置你的组件内部UI内容
        }
    }
}

方案二:RenderEffect灰度实现(API 21+)

若最低支持版本为API 21及以上,可使用RenderEffect直接添加灰度滤镜:

Surface(
    modifier = modifier
        .graphicsLayer {
            alpha = 0.8f
            renderEffect = RenderEffect.createColorFilterEffect(
                ColorMatrixColorFilter(ColorMatrix().apply { setToSaturation(0f) })
            )
        }
) {
    // 此处放置你的组件内部UI内容
}

两种方案均能达到与BlendMode.Saturation一致的视觉效果,优先推荐方案一以获得更广的兼容性。

内容的提问来源于stack exchange,提问作者Programmer123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:27:04