Android---向量圖(Vector)使用方法
阿新 • • 發佈:2019-02-03
概述
完全取代簡單的圖示,在各種解析度的螢幕上都不會失真.
使用步驟
1.先在gradle裡配置引數
目的是讓向量圖在5.0前的手機上也正常顯示
apply plugin: 'com.android.library'
android {
... ...
defaultConfig {
//配置這個引數
vectorDrawables.useSupportLibrary = true
}
... ...
}
2.drawable –> 右鍵 –> new –> vector assets裡建好。
(0)首先給佈局指定名稱空間
xmlns:app="http://schemas.android.com/apk/res-auto"
(1)給控制元件指定向量圖,必須下面用的方式。
app:srcCompat="@drawable/ic_xxx"
例如:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/fab_margin"
android:tint="@android:color/white"
app:backgroundTint="@android:color/holo_orange_light"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="@drawable/ic_add" />
</android.support .design.widget.CoordinatorLayout>
3.為向量圖動態設定顏色
(1)靜態
如果需要靜態指定顏色,在使用的地方給tint屬性賦值。
android:tint="@android:color/white"
(2)動態
在需要的地方呼叫該方法
/**
* 給使用了向量圖的ImageView設定顏色
*
* @param context 上下文
* @param vectorRid xml向量圖的id
* @param colorRid 顏色的id
* @param imageView 要設定的控制元件
*/
public static void setVectorColorImgv(Context context, int vectorRid, int colorRid, ImageView imageView) {
VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(context.getResources(),
vectorRid, context.getTheme());
//以下三種方式選一種
//1.設定單一的顏色
vectorDrawableCompat.setTint(context.getResources().getColor(colorRid));
//2.設定狀態性的,比如點選一個顏色,未點選一個顏色
//vectorDrawableCompat.setTintList(ColorStateList.valueOf(colorRid));
//3.用這個v4提供的也可,這個適用於任意的drawable著色
//DrawableCompat.setTint(vectorDrawableCompat,.getResources().getColor(colorRid));
imageView.setImageDrawable(vectorDrawableCompat);
}
例如:
//圖片初始化
Utils.setVectorColorImgv(this, R.drawable.ic_index, R.color.deep_grey, imgvBottomMainIndex);