Android---矢量图(Vector)使用方法

本文介绍了如何在Android中使用矢量图,确保图标在不同分辨率屏幕上不失真。步骤包括在gradle中配置参数以支持低版本系统,通过vector assets创建矢量资源,以及如何静态和动态地为矢量图设置颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

完全取代简单的图标,在各种分辨率的屏幕上都不会失真.

使用步骤

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值