天天看點

Android 使用SVG矢量圖下載下傳矢量圖Android studio 使用矢量圖代碼動态改變SVG顔色

下載下傳矢量圖

矢量圖,是什麼,就不用講了,不清楚,自行百度哈。

阿裡矢量圖庫 http://www.iconfont.cn/,這裡有各式各樣的矢量圖,基本能滿足我們日常用圖需求。

首先,下載下傳*.svg格式的矢量圖

Android 使用SVG矢量圖下載下傳矢量圖Android studio 使用矢量圖代碼動态改變SVG顔色

Android studio 使用矢量圖

項目中,在要放置矢量圖的目錄右擊->new->Vector Asset,如下圖

Android 使用SVG矢量圖下載下傳矢量圖Android studio 使用矢量圖代碼動态改變SVG顔色

開始轉換

Android 使用SVG矢量圖下載下傳矢量圖Android studio 使用矢量圖代碼動态改變SVG顔色

最後,生成ic_menu_collection.xml矢量圖xml檔案

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="1024.0"
    android:viewportWidth="1024.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M895.8,517.7c88.3,-91.9 88.2,-240.9 0,-332.8 -45.1,-47 -104.5,-69.9 -163.6,-68.9 -82.7,1.5 -219,115.4 -219,115.4s-140.2,-115.6 -224.9,-115.4c-57.7,0.1 -115.4,23.1 -159.4,68.9 -88.2,91.9 -88.3,240.9 0,332.8l383.5,399.3L895.8,517.7z" />
</vector>
           

使用

和圖檔一樣使用即可

代碼動态改變SVG顔色

package com.xuewei.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.widget.ImageView;

import com.xuewei.XWApplication;

/**
 * 
 * Created by Administrator on 2017/3/11.
 */

public class SVGUtils {

    public static SVGUtils svgUtils;
    private Context mContext;
    private SVGUtils(){
        mContext = XWApplication.getInstance();
    }
    public static SVGUtils getInstance(){
        if(svgUtils==null){
            svgUtils = new SVGUtils();
        }
        return svgUtils;
    }


    /**
     * 改變SVG圖檔着色
     * @param imageView
     * @param iconResId svg資源id
     * @param color 期望的着色
     */
    public void changeSVGColor(ImageView imageView,int iconResId,int color){
        Drawable drawable = ContextCompat.getDrawable(mContext, iconResId);
        imageView.setImageDrawable(drawable);
        Drawable.ConstantState state = drawable.getConstantState();
        Drawable drawable1 = DrawableCompat.wrap(state == null ? drawable : state.newDrawable()).mutate();
        drawable1.setBounds(, , drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        DrawableCompat.setTint(drawable1, ContextCompat.getColor(mContext, color));
        imageView.setImageDrawable(drawable1);
    }
}
           

調用

if(groupXueWei.getCollection()){
            SVGUtils.getInstance().changeSVGColor(holder.collectionIcon,R.drawable.ic_collection,R.color.collection);
        }else{
            SVGUtils.getInstance().changeSVGColor(holder.collectionIcon,R.drawable.ic_collection,R.color.unCollection);
        }