View 体系
View 体系 · androidx.core
VectorDrawable:矢量图Core 1.20.0-alpha01
XML 矢量图资源与 VectorDrawableCompat 的兼容用法。
最后更新 2026-08-01
复制即用
定义矢量图(res/drawable/ic_arrow.xml):
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M12,4l-1.41,1.41L16.17,11H4v2h12.17l-5.58,5.59L12,20l8,-8z" />
</vector>使用:
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/ic_arrow" />代码中获取:
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
VectorDrawableCompat drawable =
VectorDrawableCompat.create(getResources(), R.drawable.ic_arrow, getTheme());
imageView.setImageDrawable(drawable);动画矢量图
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_arrow">
<target
android:name="arrow_group"
android:animation="@anim/arrow_rotate" />
</animated-vector>配合 AnimatedVectorDrawableCompat 在旧设备上运行。
常见陷阱
- 忘 app:srcCompat:
android:src在旧设备可能不渲染 VectorDrawableCompat。 - 路径过复杂:手动写 pathData 易错,用 Android Studio Vector Asset 从 SVG 转换。
- viewport 与尺寸不匹配:
viewportWidth/Height是坐标空间,width/height是显示尺寸,两者独立。
要点
viewportWidth/Height定义坐标空间,width/height定义显示尺寸;绘制路径用pathData。- 优点:多密度无失真、文件小、可着色调色(
tint)。 - 旧设备兼容:
VectorDrawableCompat与AnimatedVectorDrawableCompat。 - 与
app:srcCompat配合可避免旧版本兼容问题。 - 复杂路径建议用 Android Studio 的 Vector Asset 工具从 SVG 转换。