Compose中Icons.Rounded.StarHalf等双色图标无法应用Tint求助
问题描述
我尝试根据当前深色/浅色主题为图标应用自定义tint颜色,多数图标可正常生效,但Icons.Rounded.StarHalf图标无法应用该颜色。
先尝试使用Icon组件:
Icon( imageVector = Icons.Rounded.StarHalf, contentDescription = null, tint = iconTintColor, modifier = Modifier .selectable( indication = if (isIndicator) LocalIndication.current else null, interactionSource = remember { MutableInteractionSource() }, selected = isSelected, ) .width(starSize) .height(starSize) )
之后换用Image组件,问题依然存在:
Image( imageVector = Icons.Rounded.StarHalf, contentDescription = null, colorFilter = ColorFilter.tint(iconTintColor), modifier = Modifier .selectable( indication = if (isIndicator) LocalIndication.current else null, interactionSource = remember { MutableInteractionSource() }, selected = isSelected, ) .width(starSize) .height(starSize) )
请问如何强制设置该星星图标透明部分的颜色?
(预览图:半星图标显示效果)
解决方案
Icons.Rounded.StarHalf的空白区域并非图标矢量路径的一部分,所以tint和ColorFilter.tint()只会对已有路径的半星区域生效。要给空白部分上色,可采用以下两种方法:
叠加图标实现自定义半星
用一个完整的Star图标作为底层,设置你想要的空白区域颜色,再叠加上StarHalf图标并设置高亮颜色:Box(modifier = Modifier .selectable( indication = if (isIndicator) LocalIndication.current else null, interactionSource = remember { MutableInteractionSource() }, selected = isSelected, ) .width(starSize) .height(starSize)) { // 底层空白星星,设置空白区域的目标颜色 Icon( imageVector = Icons.Rounded.Star, contentDescription = null, tint = emptyStarColor, modifier = Modifier.matchParentSize() ) // 上层半星,设置高亮区域的颜色 Icon( imageVector = Icons.Rounded.StarHalf, contentDescription = null, tint = highlightedStarColor, modifier = Modifier.matchParentSize() ) }自定义矢量图标
若需要完全自定义的半星样式,可直接修改StarHalf的矢量路径,将空白部分添加为路径的一部分,这样就能用tint统一为整个图标上色。你可以通过Android Studio的Vector Asset工具编辑图标,或者在代码中直接修改ImageVector的路径数据。
内容的提问来源于stack exchange,提问作者Ahmed Nezhi
相关产品推荐
相关产品推荐

