Android Compose 如何实现支持纯色、线性渐变、URL的统一Image组件
实现思路
把三类数据源统一封装为自定义数据源类型,直接适配Coil的加载逻辑,不需要分支判断实例化多个Image组件,所有场景共用同一套组件渲染逻辑即可。
实现步骤
1. 定义统一数据源密封类
先封装三类数据源为密封类,避免类型判断的魔法值,也方便后续扩展参数:
sealed class ImageSource { // 纯色填充源 data class Solid(val color: Color) : ImageSource() // 渐变填充源,也可以按需扩展角度、颜色位置等参数 data class Gradient(val gradientBrush: Brush) : ImageSource() // URL图片源,可按需扩展占位图、错误图等参数 data class Url(val link: String, val placeholder: Drawable? = null, val error: Drawable? = null) : ImageSource() }
2. 扩展Coil请求适配自定义数据源
Coil本身原生支持直接传入Color、Brush作为加载数据源,我们只需要给Coil的请求构造器加扩展方法,自动匹配数据源类型配置参数即可:
fun ImageRequest.Builder.applySource(source: ImageSource): ImageRequest.Builder { return when (source) { is ImageSource.Solid -> data(source.color) is ImageSource.Gradient -> data(source.gradientBrush) is ImageSource.Url -> data(source.link) .placeholder(source.placeholder) .error(source.error) } }
3. 封装统一Image组件
直接基于Coil的AsyncImage封装统一组件,所有场景共用同一个组件实例:
@Composable fun UnifiedImage( source: ImageSource, contentDescription: String?, modifier: Modifier = Modifier, contentScale: ContentScale = ContentScale.Fit, crossFadeEnable: Boolean = true ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .applySource(source) .apply { if (crossFadeEnable) crossfade(true) } .build(), contentDescription = contentDescription, modifier = modifier, contentScale = contentScale ) }
4. 调用示例
使用时直接传入对应类型的ImageSource即可,不需要再写when分支实例化Image:
// 纯色示例 UnifiedImage( source = ImageSource.Solid(Color(0xFFFF0000)), contentDescription = null, modifier = Modifier.size(100.dp) ) // 渐变示例 UnifiedImage( source = ImageSource.Gradient( Brush.linearGradient(listOf(Color.Blue, Color.Cyan)) ), contentDescription = null, modifier = Modifier.size(100.dp) ) // URL图片示例 UnifiedImage( source = ImageSource.Url( link = "https://test.com/test.png", placeholder = painterResource(R.drawable.ic_placeholder).asDrawable() ), contentDescription = "测试图", modifier = Modifier.size(100.dp) )
其他说明
如果是View体系的实现,逻辑完全一致:自定义AppCompatImageView,暴露setImageSource方法,内部根据传入的ImageSource构造Coil请求调用load方法即可,不需要分支实例化不同ImageView。
内容的提问来源于stack exchange,提问作者PhongBM
相关产品推荐
相关产品推荐

