Android SVG

作者: MinicupSimon | 来源:发表于2018-01-05 15:49 被阅读2009次

SVG 意为可缩放矢量图形(Scalable Vector Graphics)。
SVG 使用 XML 格式定义图像。

*如何引用SVG


  1. 先创建一个SVG资源,这里我们用AS自带的一些资源。


    image.png
  2. 这里我们选择一个简单的图形,命名为triangle


    image.png
  1. 在drawable目录下会生成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

*静态VectorDrawable在XML中的定义


VectorDrawable 官方介绍

官方给的例子

 <vector xmlns:android="http://schemas.android.com/apk/res/android"
     android:name="triangle"//定义矢量图的名称
     android:height="64dp"//drawable的固定高度,支持所有的尺寸单位,一般使用dp
     android:width="64dp"//drawable的固定宽度,支持所有的尺寸单位,一般使用dp
     android:viewportHeight="600"//视图的高度,可以理解为画布的高度
     android:viewportWidth="600" >//视图的宽度,下面的pathData中的内容便会在600宽高的画布内操作
     <group //定义一个组,可以包含path 及子group, 同时可以定义转换信息,如旋转,伸缩,位移
         android:name="rotationGroup"//组名
         android:pivotX="300.0"//X坐标中心点,默认为0
         android:pivotY="300.0"//Y坐标中心点,默认为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>
 </vector>

效果:


image.png
我们来解析一下数据:M300,70 l 0,-70 70,70 0,0 -70,70z

先来了解一下相关的指令:
M = moveto 相当于 android Path 里的moveTo(),用于移动起始点
L = lineto 相当于 android Path 里的lineTo(),用于画线
H = horizontal lineto 用于画水平线
V = vertical lineto 用于画竖直线
C = curveto 相当于cubicTo(),三次贝塞尔曲线
S = smooth curveto 同样三次贝塞尔曲线,更平滑
Q = quadratic Belzier curve quadTo(),二次贝塞尔曲线
T = smooth quadratic Belzier curveto 同样二次贝塞尔曲线,更平滑
A = elliptical Arc 相当于arcTo(),用于画弧
Z = closepath 相当于closeTo(),关闭path

作者:Wavky
链接:https://www.jianshu.com/p/1bb7707d0291
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

坐标轴为以(0,0)为中心,X轴水平向右,Y轴水平向下
所有指令大小写均可。大写绝对定位,参照全局坐标系;小写相对定位,参照父容器坐标系
指令和数据间的空格可以省略
同一指令出现多次可以只用一个

(1). M指令
(2). l 指令(小写的L) (l 0, -70 70,70 0,0 -70,70z 相当于 l 0,-70 l 70,70 l 0,0 l -70,70z)
(3). z指令

  1. M300, 70 : 坐标移动到(300, 70)这个点上


    image.png
  1. l 0,-70


    image.png
  1. l 70,70


    image.png
  1. l 0, 0 (没有移动,如果动画的propertyXName="pathType"时这步操作起占位作用)
  1. l -70,70


    image.png

6.z 闭合


image.png

7.设置填充颜色

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

8 以中心点顺时针旋转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.完成
需要说明,同一形状实现的方式很多,以上例子只是官方给的例子,在这只做分析,不论是否合理。
以下方式实现效果一样,自己脑补吧。

    <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:文章一开始从系统引入的svg实现步骤如下图。


svg.gif

*动态AnimatedVectorDrawable


我们来看看怎么让SVG动起来, 还以上面三角形为例,先看效果

svg.gif

以上GIF展示了简单的旋转,伸缩,平移,透明度的动画。代码如下:
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:针对name的目标做动画 name在上面svg文件中定义-->
    <!--透明度动画作用在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动画的path需要添加到group标签中才有效果-->
    <!--scale,rotate动画的pivot 在group中设置-->
    <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();//启动动画
  }
  //添加事件监听
  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);
    }
  });           

*高级动画(trimPath)


1. trimPathStart

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

2.trimPathOffset

android:trimPathStart="0.1"
android:trimPathOffset="0.5"
把path的原点移动到50%的位置,再以此为原点去除掉0%位置到10%位置的path

3. trimPathEnd

android:trimPathEnd="0.9"
android:trimPathOffset="0.5"
把path的原点移动到50%的位置,再以此为原点去除掉90%位置到100%位置的path

SearchBar 拿个人觉得比较实用的网上一例子,个人修改了一下,看着更符合实际情况:
searchbar.gif

首先准备VectorDrawable,两个Path:一个放大镜,一条线(通过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"/>

接下来动态处理动画

        //获得相应的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;//默认状态为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是此消彼长的关系)

<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之后系统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"//progressBar的动画效果
        android:animation="@anim/progress_indeterminate_material" />

    <target
        android:name="root"//同时也在自旋转
        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">//根据当前主题的colorControlActivated所设置的颜色来着色
   
    <group
        android:name="root"
        android:translateX="24.0" //将画布原点移动到中心位置
        android:translateY="24.0" >
        <path
            android:name="progressBar"
            android:fillColor="#00000000"
            //顺时针画两个半圆, 这里巧用了画布的平移。逻辑清晰,计算简单
            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"//svg此时什么都不显示
            android:trimPathOffset="0"
            android:trimPathStart="0" />
    </group>
</vector>
效果图

progress_indeterminate_material.xml

<set xmlns:android="http://schemas.android.com/apk/res/android" >
    //以下两个动画都是从valueFrom:0到valueTo:0.75,但由于指定了不同的Interpolator
    //最后显示的结果progressbar时长时短。
    <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" />

网上效果不错的例子:
模拟三球仪

earth.gif

兼容性问题


Vector图像刚发布的时候,是只支持Android 5.0+的设备
不过自从AppCompat 23.2之后,我们只需要引入com.android.support:appcompat-v7:23.2.0以上的版本 的兼容包,Vector可以使用于Android 2.1以上的所有系统。

经测试静态VectorDrawable在5.0前后运行都正常,只不过5.0之前的版本图片有点模糊
compileSdkVersion 24
buildToolsVersion "25.0.2"
compile 'com.android.support:appcompat-v7:25.3.1'
未使用 vectorDrawables.useSupportLibrary = true
未使用
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
动态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变为AppCompatImageView(support-v7), AnimatedVectorDrawable变为AnimatedVectorDrawableCompat(animated-vector-drawable), VectorDrawable变为VectorDrawableCompat(support-vector-drawable)

*相关资源


Android SVG to VectorDrawable
Online SVG Editor
IconFont
VectAlign 比较牛
在线SVG动画编辑

shapeshifter.gif

*参考


AnimatedVectorDrawable的一些碎碎念 兼容性
Android Vector曲折的兼容之路
android中的SVG图像的各个属性意义
【Android 进阶】SVG 的使用以及绘制动画
github AnimatedSvgView
AnimatedVectorDrawable实现可爱的图钉跳跃动画
github vector-compat

相关文章

网友评论

    本文标题:Android SVG

    本文链接:https://www.haomeiwen.com/subject/jznjnxtx.html