Android SVG

SVG 意為可縮放矢量圖形(Scalable Vector Graphics)。
SVG 使用 XML 格式定義圖像。

*如何引用SVG


  1. 先創(chuàng)建一個(gè)SVG資源,這里我們用AS自帶的一些資源。


    image.png
  2. 這里我們選擇一個(gè)簡(jiǎn)單的圖形,命名為triangle


    image.png
  1. 在drawable目錄下會(huì)生成triangle.xml文件。
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M3,4l9,16 9,-16L3,4zM6.38,6h11.25L12,16 6.38,6z"/>
</vector>
  1. 在layout文件中引入
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/triangle"
        />
</LinearLayout>
image.png

*靜態(tài)VectorDrawable在XML中的定義


VectorDrawable 官方介紹

官方給的例子

 <vector xmlns:android="http://schemas.android.com/apk/res/android"
     android:name="triangle"http://定義矢量圖的名稱
     android:height="64dp"http://drawable的固定高度,支持所有的尺寸單位,一般使用dp
     android:width="64dp"http://drawable的固定寬度,支持所有的尺寸單位,一般使用dp
     android:viewportHeight="600"http://視圖的高度,可以理解為畫布的高度
     android:viewportWidth="600" >//視圖的寬度,下面的pathData中的內(nèi)容便會(huì)在600寬高的畫布內(nèi)操作
     <group //定義一個(gè)組,可以包含path 及子group, 同時(shí)可以定義轉(zhuǎn)換信息,如旋轉(zhuǎn),伸縮,位移
         android:name="rotationGroup"http://組名
         android:pivotX="300.0"http://X坐標(biāo)中心點(diǎn),默認(rèn)為0
         android:pivotY="300.0"http://Y坐標(biāo)中心點(diǎn),默認(rèn)為0
         android:rotation="45.0" >//旋轉(zhuǎn)角度,順時(shí)針
         <path
             android:name="v"http://路徑的名稱
             android:fillColor="#000000"http://填充顏色
             android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />//路徑的數(shù)據(jù)
     </group>
 </vector>

效果:


image.png
我們來解析一下數(shù)據(jù):M300,70 l 0,-70 70,70 0,0 -70,70z

先來了解一下相關(guān)的指令:
M = moveto 相當(dāng)于 android Path 里的moveTo(),用于移動(dòng)起始點(diǎn)
L = lineto 相當(dāng)于 android Path 里的lineTo(),用于畫線
H = horizontal lineto 用于畫水平線
V = vertical lineto 用于畫豎直線
C = curveto 相當(dāng)于cubicTo(),三次貝塞爾曲線
S = smooth curveto 同樣三次貝塞爾曲線,更平滑
Q = quadratic Belzier curve quadTo(),二次貝塞爾曲線
T = smooth quadratic Belzier curveto 同樣二次貝塞爾曲線,更平滑
A = elliptical Arc 相當(dāng)于arcTo(),用于畫弧
Z = closepath 相當(dāng)于closeTo(),關(guān)閉path

坐標(biāo)軸為以(0,0)為中心,X軸水平向右,Y軸水平向下
所有指令大小寫均可。大寫絕對(duì)定位,參照全局坐標(biāo)系;小寫相對(duì)定位,參照父容器坐標(biāo)系
指令和數(shù)據(jù)間的空格可以省略
同一指令出現(xiàn)多次可以只用一個(gè)

(1). M指令
(2). l 指令(小寫的L) (l 0, -70 70,70 0,0 -70,70z 相當(dāng)于 l 0,-70 l 70,70 l 0,0 l -70,70z)
(3). z指令

  1. M300, 70 : 坐標(biāo)移動(dòng)到(300, 70)這個(gè)點(diǎn)上


    image.png
  1. l 0,-70


    image.png
  1. l 70,70


    image.png
  1. l 0, 0 (沒有移動(dòng),如果動(dòng)畫的propertyXName="pathType"時(shí)這步操作起占位作用)
  1. l -70,70


    image.png

6.z 閉合


image.png

7.設(shè)置填充顏色

        <path
            android:name="v"
            android:fillColor="#000000"
            android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
image.png

8 以中心點(diǎn)順時(shí)針旋轉(zhuǎn)45度

    <group
        android:name="rotationGroup"
        android:pivotX="300.0"
        android:pivotY="300.0"
        android:rotation="45.0">
        <path
            android:name="v"
            android:fillColor="#000000"
            android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
    </group>
image.png

9.完成
需要說明,同一形狀實(shí)現(xiàn)的方式很多,以上例子只是官方給的例子,在這只做分析,不論是否合理。
以下方式實(shí)現(xiàn)效果一樣,自己腦補(bǔ)吧。

    <group
        android:name="rotationGroup"
        android:pivotX="300.0"
        android:pivotY="300.0"
        android:rotation="45.0">
        <path
            android:name="v"
            android:fillColor="#000000"
            android:pathData="M300,0 V140 l70,-70z" />
    </group>

ps:文章一開始從系統(tǒng)引入的svg實(shí)現(xiàn)步驟如下圖。


svg.gif

*動(dòng)態(tài)AnimatedVectorDrawable


我們來看看怎么讓SVG動(dòng)起來, 還以上面三角形為例,先看效果

svg.gif

以上GIF展示了簡(jiǎn)單的旋轉(zhuǎn),伸縮,平移,透明度的動(dòng)畫。代碼如下:
Activity布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:srcCompat="@drawable/animate_vector" />
</LinearLayout>

R.drawable.animate_vector:

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/triangle">
    <!--target:針對(duì)name的目標(biāo)做動(dòng)畫 name在上面svg文件中定義-->
    <!--透明度動(dòng)畫作用在group及path上不起作用-->
    <target
        android:animation="@animator/alpha"
        android:name="triangle" />
    <target
        android:animation="@animator/scalex"
        android:name="group" />
    <target
        android:animation="@animator/scaley"
        android:name="group" />
    <target
        android:animation="@animator/rotate"
        android:name="group" />
    <target
        android:animation="@animator/translate"
        android:name="group" />
</animated-vector>

R.drawable.triangle:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:name="triangle"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <!--scale,translate, rotate動(dòng)畫的path需要添加到group標(biāo)簽中才有效果-->
    <!--scale,rotate動(dòng)畫的pivot 在group中設(shè)置-->
    <group
        android:name="group"
        android:scaleX="0.5"
        android:scaleY="0.5"
        android:pivotX="12"
        android:pivotY="12">
        <path
            android:name="path"
            android:strokeColor="@color/colorPrimary"
            android:strokeWidth="0.2"
            android:fillColor="#FF000000"
            android:pathData="M3,4l9,16 9,-16L3,4zM6.38,6h11.25L12,16 6.38,6z"/>
    </group>
</vector>
  ImageView mImageView = (ImageView) findViewById(R.id.imageView);
  Drawable background = mImageView.getDrawable();
  if(background instanceof Animatable){
      ((Animatable) background).start();//啟動(dòng)動(dòng)畫
  }
  //添加事件監(jiān)聽
  AnimatedVectorDrawableCompat drawable= (AnimatedVectorDrawableCompat) background;
  drawable.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
    @Override
    public void onAnimationStart(Drawable drawable) {
        super.onAnimationStart(drawable);
        Toast.makeText(MainActivity.this, "start", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onAnimationEnd(Drawable drawable) {
        super.onAnimationEnd(drawable);
        Toast.makeText(MainActivity.this, "end", Toast.LENGTH_SHORT).show();
        compat.unregisterAnimationCallback(this);
    }
  });           

*高級(jí)動(dòng)畫(trimPath)


1. trimPathStart

android:trimPathStart="0.1"
從path的0%開始去除掉0%位置到10%位置的path

2.trimPathOffset

android:trimPathStart="0.1"
android:trimPathOffset="0.5"
把path的原點(diǎn)移動(dòng)到50%的位置,再以此為原點(diǎn)去除掉0%位置到10%位置的path

3. trimPathEnd

android:trimPathEnd="0.9"
android:trimPathOffset="0.5"
把path的原點(diǎn)移動(dòng)到50%的位置,再以此為原點(diǎn)去除掉90%位置到100%位置的path

SearchBar 拿個(gè)人覺得比較實(shí)用的網(wǎng)上一例子,個(gè)人修改了一下,看著更符合實(shí)際情況:
searchbar.gif

首先準(zhǔn)備VectorDrawable,兩個(gè)Path:一個(gè)放大鏡,一條線(通過trimPathStart="1"隱藏)
searchbar.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="150dp"
        android:height="24dp"
        android:viewportHeight="24"
        android:viewportWidth="150">
    <path
        android:name="search"
        android:pathData="M141,17 A9,9 0 1,1 142,16 L149,23"
        android:strokeAlpha="0.8"
        android:strokeColor="#000000"
        android:strokeLineCap="round"
        android:strokeWidth="2"/>
    <path
        android:name="bar"
        android:pathData="M0,23 L149,23"
        android:strokeAlpha="0.8"
        android:trimPathStart="1"
        android:strokeColor="#000000"
        android:strokeLineCap="square"
        android:strokeWidth="2"/>
</vector>

布局文件

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startAnim"
        app:srcCompat="@drawable/searchbar"/>

接下來動(dòng)態(tài)處理動(dòng)畫

        //獲得相應(yīng)的AnimatedVectorDrawableCompat
        AnimatedVectorDrawableCompat unfocus = AnimatedVectorDrawableCompat.create(this, R.drawable.searchbar_unfocus);
        AnimatedVectorDrawableCompat focus = AnimatedVectorDrawableCompat.create(this, R.drawable.searchbar_focus);

        private static final int UNFOCUS = 300;
        private static final int FOCUS = 948;
        int state = UNFOCUS;//默認(rèn)狀態(tài)為unfocus

        public void startAnim(View view) {
                if (view instanceof AppCompatImageView) {
                    if (state == UNFOCUS) {
                        state = FOCUS;
                        focus((AppCompatImageView) view);
                    } else if (state == FOCUS) {
                        state = UNFOCUS;
                        unfocus((AppCompatImageView) view);
                    }
                }
        }

        private void unfocus(AppCompatImageView view) {
            view.setImageDrawable(unfocus);
            unfocus.start();
        }

        private void focus(ImageView view) {
            view.setImageDrawable(focus);
            focus.start();
        }

searchbar_focus.xml

<animated-vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/searchbar">

    <target
        android:name="search"
        android:animation="@animator/anim_searchbar_0_1"/>

    <target
        android:name="bar"
        android:animation="@animator/anim_searchbar_1_0"/>

</animated-vector>

searchbar_unfocus.xml(searchbar_focus.xml的逆操作)

<animated-vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/searchbar">

    <target
        android:name="search"
        android:animation="@animator/anim_searchbar_1_0"/>

    <target
        android:name="bar"
        android:animation="@animator/anim_searchbar_0_1"/>

</animated-vector>

anim_searchbar_0_1.xml

<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="trimPathStart"
    android:valueFrom="0"
    android:valueTo="1"
    android:valueType="floatType"/>

anim_searchbar_1_0.xml (放大鏡與底線的trimPathStart是此消彼長(zhǎng)的關(guān)系)

<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="trimPathStart"
    android:valueFrom="1"
    android:valueTo="0"
    android:valueType="floatType"/>
5.0之后系統(tǒng)ProgressBar
progress.gif

progress_medium_material.xml

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/vector_drawable_progress_bar_medium" >

    <target
        android:name="progressBar"http://progressBar的動(dòng)畫效果
        android:animation="@anim/progress_indeterminate_material" />

    <target
        android:name="root"http://同時(shí)也在自旋轉(zhuǎn)
        android:animation="@anim/progress_indeterminate_rotation_material" />

</animated-vector>

vector_drawable_progress_bar_medium.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:height="48dp"
        android:width="48dp"
        android:viewportHeight="48"
        android:viewportWidth="48"
        android:tint="?attr/colorControlActivated">//根據(jù)當(dāng)前主題的colorControlActivated所設(shè)置的顏色來著色
   
    <group
        android:name="root"
        android:translateX="24.0" //將畫布原點(diǎn)移動(dòng)到中心位置
        android:translateY="24.0" >
        <path
            android:name="progressBar"
            android:fillColor="#00000000"
            //順時(shí)針畫兩個(gè)半圓, 這里巧用了畫布的平移。邏輯清晰,計(jì)算簡(jiǎn)單
            android:pathData="M0, 0 m 0, -18 a 18,18 0 1,1 0,36 a 18,18 0 1,1 0,-36"
            android:strokeColor="#ffffff"
            android:strokeLineCap="square"
            android:strokeLineJoin="miter"
            android:strokeWidth="4"
            android:trimPathEnd="0"http://svg此時(shí)什么都不顯示
            android:trimPathOffset="0"
            android:trimPathStart="0" />
    </group>
</vector>
效果圖

progress_indeterminate_material.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >
    //以下兩個(gè)動(dòng)畫都是從valueFrom:0到valueTo:0.75,但由于指定了不同的Interpolator
    //最后顯示的結(jié)果progressbar時(shí)長(zhǎng)時(shí)短。
    <objectAnimator
        android:duration="1333"
        android:interpolator="@interpolator/trim_start_interpolator"
        android:propertyName="trimPathStart"
        android:repeatCount="-1"
        android:valueFrom="0"
        android:valueTo="0.75"
        android:valueType="floatType" />
    <objectAnimator
        android:duration="1333"
        android:interpolator="@interpolator/trim_end_interpolator"
        android:propertyName="trimPathEnd"
        android:repeatCount="-1"
        android:valueFrom="0"
        android:valueTo="0.75"
        android:valueType="floatType" />

    <objectAnimator
        android:duration="1333"
        android:interpolator="@android:anim/linear_interpolator"
        android:propertyName="trimPathOffset"
        android:repeatCount="-1"
        android:valueFrom="0"
        android:valueTo="0.25"
        android:valueType="floatType" />

</set>

progress_indeterminate_rotation_material.xml

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="4444"
    android:interpolator="@android:anim/linear_interpolator"
    android:propertyName="rotation"
    android:repeatCount="-1"
    android:valueFrom="0"
    android:valueTo="720"
    android:valueType="floatType" />

網(wǎng)上效果不錯(cuò)的例子:
模擬三球儀

earth.gif


兼容性問題


Vector圖像剛發(fā)布的時(shí)候,是只支持Android 5.0+的設(shè)備
不過自從AppCompat 23.2之后,我們只需要引入com.android.support:appcompat-v7:23.2.0以上的版本 的兼容包,Vector可以使用于Android 2.1以上的所有系統(tǒng)。

經(jīng)測(cè)試靜態(tài)VectorDrawable在5.0前后運(yùn)行都正常,只不過5.0之前的版本圖片有點(diǎn)模糊
compileSdkVersion 24
buildToolsVersion "25.0.2"
compile 'com.android.support:appcompat-v7:25.3.1'
未使用 vectorDrawables.useSupportLibrary = true
未使用
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
動(dòng)態(tài)AnimatedVectorDrawable
5.0后正常

5.0前異常
XmlPullParserException: Binary XML file line #2: invalid drawable tag animated-vector
android.content.res.Resources$NotFoundException: File res/drawable/animatevector.xml from drawable resource ID #0x7f020053

解決方法:
    compile 'com.android.support:appcompat-v7:XXX'
    defaultConfig {
      vectorDrawables.useSupportLibrary = true
    }
    android:src=""改為app:srcCompat=""
    下面代碼用不用都可以
    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }
Activity需要繼承AppCompatActivity: ImageView變?yōu)锳ppCompatImageView(support-v7), AnimatedVectorDrawable變?yōu)锳nimatedVectorDrawableCompat(animated-vector-drawable), VectorDrawable變?yōu)閂ectorDrawableCompat(support-vector-drawable)

*相關(guān)資源


Android SVG to VectorDrawable
Online SVG Editor
IconFont
VectAlign 比較牛
在線SVG動(dòng)畫編輯

shapeshifter.gif


*參考


AnimatedVectorDrawable的一些碎碎念 兼容性
Android Vector曲折的兼容之路
android中的SVG圖像的各個(gè)屬性意義
【Android 進(jìn)階】SVG 的使用以及繪制動(dòng)畫
github AnimatedSvgView
AnimatedVectorDrawable實(shí)現(xiàn)可愛的圖釘跳躍動(dòng)畫
github vector-compat

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容