Android and playing SVG animation

2020-02-02 12:00发布

问题:

I'm writing an Android application and I'd like to play a simple SVG animation. I'm aware that Android does not offer SVG support; what are my options here?

回答1:

Starting from Android Lollipop (API level 21) it is possible to implement using AnimatedVectorDrawable.

There are also tools that will help to animate vector drawable shapeshifter and blog post from the author of the tool shapeshifter An Introduction to Icon Animation Techniques.



回答2:

  1. Take your SVG image and convert it to a VectorDrawable here
  2. Add your downloaded XML file to your project and see how it looks. Heres an example of an VectorDrawable prepared for a rotation and path morph animation:

    <vector xmlns:android="http://schemas.android.com/apk/res/android"
     android:height="64dp"
     android:width="64dp"
     android:viewportHeight="600"
     android:viewportWidth="600" >
     <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>
    

3 Now create a AnimatedVectorDrawable where you refer to the rotationGroup and path morph in the created VectorDrawable

<?xml version="1.0" encoding="UTF-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/vectordrawable">
   <target android:name="rotationGroup" android:animation="@anim/rotation" />
   <target android:name="v" android:animation="@anim/path_morph" />
</animated-vector>

4 Create two animators for the AnimatedVectorDrawable:

<objectAnimator
    android:duration="6000"
    android:propertyName="rotation"
    android:valueFrom="0"
    android:valueTo="360" />

and :

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="3000"
        android:propertyName="pathData"
        android:valueFrom="M300,70 l 0,-70 70,70 0,0 -70,70z"
        android:valueTo="M300,70 l 0,-70 70,0  0,140 -70,0 z"
        android:valueType="pathType"/>
 </set>

(It is also possible to define all this in one file, refer to the docs here)

One way to then start the animation is by getting the drawable from the view and run start().



回答3:

Use VectorDrawable. if target is under Lollipop use support library.