如何为多path组成的vector drawable填充纯色或渐变 含Jetpack Compose方案
传统View体系Vector Drawable实现方案
你当前的多个path均为独立线段,未形成可填充的闭合区域,可按以下方案实现填充:
- 合并所有路径为单个闭合路径:将所有
pathData的点位按绘制顺序拼接,末尾添加Z指令标识路径闭合,为该路径添加android:fillColor属性指定填充色即可。如果需要保留原有的描边效果,可将合并后的填充路径放在矢量图的最底层,原有描边路径放在上层绘制。 - 若形状存在镂空或路径交叉的情况,给合并后的路径添加
android:fillType="evenOdd"属性即可实现正确的镂空填充效果。
示例代码(以你给出的正方形为例):
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"> <!-- 底层填充路径 --> <path android:fillColor="#FF0000" android:pathData="M10,10 L98,10 L98,98 L10,98 Z"/> <!-- 上层原有描边路径 --> <path android:strokeColor="#000000" android:strokeWidth="2" android:pathData="M10,10 98, 10"/> <path android:strokeColor="#000000" android:strokeWidth="2" android:pathData="M98,10 98, 98"/> <path android:strokeColor="#000000" android:strokeWidth="2" android:pathData="M98,98 10, 98"/> <path android:strokeColor="#000000" android:strokeWidth="2" android:pathData="M10,98 10, 10"/> </vector>
Jetpack Compose实现方案
核心逻辑和View体系一致,先构建合并后的闭合路径完成填充,再绘制原有描边即可,示例代码如下:
Box(modifier = Modifier.size(108.dp)) { Canvas(modifier = Modifier.fillMaxSize()) { val strokeWidth = 2.dp.toPx() // 构建填充用闭合路径 val fillPath = Path().apply { moveTo(10f, 10f) lineTo(98f, 10f) lineTo(98f, 98f) lineTo(10f, 98f) close() // 对应矢量路径中的Z指令,闭合路径 // 复杂形状按绘制顺序依次添加所有路径点位即可 } // 先绘制填充背景 drawPath( path = fillPath, color = Color.Red ) // 再绘制原有描边 drawLine( start = Offset(10f,10f), end = Offset(98f,10f), color = Color.Black, strokeWidth = strokeWidth ) drawLine( start = Offset(98f,10f), end = Offset(98f,98f), color = Color.Black, strokeWidth = strokeWidth ) drawLine( start = Offset(98f,98f), end = Offset(10f,98f), color = Color.Black, strokeWidth = strokeWidth ) drawLine( start = Offset(10f,98f), end = Offset(10f,10f), color = Color.Black, strokeWidth = strokeWidth ) } }
如果路径存在镂空需求,给Path设置fillType = PathFillType.EvenOdd即可实现正确的填充效果。
内容的提问来源于stack exchange,提问作者Richard Onslow Roper
相关产品推荐
相关产品推荐

