如何在Jetpack Compose中让VectorDrawable部分颜色不受Tint影响?
如何在Jetpack Compose中让VectorDrawable的部分路径不受Tint影响
方案一:拆分Drawable并组合(最直观可靠)
把你的ic_check.xml拆成两个独立的VectorDrawable,分别控制背景和对勾:
ic_check_background.xml(仅背景圆圈):
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="20dp" android:height="20dp" android:viewportWidth="20" android:viewportHeight="20"> <path android:fillColor="#2D3296" android:pathData="M10,0C4.48,0 0,4.48 0,10C0,15.52 4.48,20 10,20C15.52,20 20,15.52 20,10C20,4.48 15.52,0 10,0Z" /> </vector>
ic_check_mark.xml(仅对勾):
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="20dp" android:height="20dp" android:viewportWidth="20" android:viewportHeight="20"> <path android:fillColor="#FFFFFF" android:pathData="M8,15L3,10L4.41,8.59L8,12.17L15.59,4.58L17,6L8,15Z" /> </vector>
在Compose中用Box组合两个Icon,分别设置颜色:
Box(modifier = Modifier.size(20.dp)) { Icon( imageVector = ImageVector.vectorResource(R.drawable.ic_check_background), contentDescription = "Check background", tint = Color.Red ) Icon( imageVector = ImageVector.vectorResource(R.drawable.ic_check_mark), contentDescription = "Check mark", tint = Color.White ) }
方案二:修改ImageVector的单个路径颜色
通过mutate()方法直接修改加载后的ImageVector的特定路径颜色,无需改动原Drawable:
// 加载并修改Icon资源 val checkIcon = ImageVector.vectorResource(R.drawable.ic_check).mutate() // 第一个路径是背景,修改为目标颜色 checkIcon.paths.firstOrNull()?.fillColor = SolidColor(Color.Red) // 第二个路径保持原白色,无需修改 Icon( imageVector = checkIcon, contentDescription = null, modifier = Modifier.size(20.dp), tint = Color.Unspecified // 必须设为Unspecified,避免全局tint覆盖自定义颜色 )
方案三:通过混合模式控制Tint作用范围
修改原VectorDrawable的背景路径为纯黑色,对勾保持白色,再用混合模式让Tint只作用于黑色区域:
- 修改
ic_check.xml:
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="20dp" android:height="20dp" android:viewportWidth="20" android:viewportHeight="20"> <path android:fillColor="#FF000000" <!-- 背景改为纯黑 --> android:pathData="M10,0C4.48,0 0,4.48 0,10C0,15.52 4.48,20 10,20C15.52,20 20,15.52 20,10C20,4.48 15.52,0 10,0ZM8,15L3,10L4.41,8.59L8,12.17L15.59,4.58L17,6L8,15Z" /> <path android:fillColor="#FFFFFF" android:pathData="M8,15L3,10L4.41,8.59L8,12.17L15.59,4.58L17,6L8,15Z" /> </vector>
- 在Compose中设置Tint和混合模式:
Icon( imageVector = ImageVector.vectorResource(R.drawable.ic_check), contentDescription = null, modifier = Modifier.size(20.dp), tint = Color.Red, tintBlendMode = BlendMode.SrcIn )
SrcIn混合模式会让Tint仅作用于原Drawable中的不透明黑色区域,白色对勾会保留原本颜色。
内容的提问来源于stack exchange,提问作者Arst
相关产品推荐
相关产品推荐

