隨著互聯網技術的不斷進步,Android的Vector圖像的時代已經到來. 在Google的最新支持庫v23.2中, AppCompat類已經使用Vector圖像, 使得AAR包減少9%, 大約70KB, 惠及所有高版本的應用. 當然我們也可以使用Vector, 瘦身應用. Vector圖像是SVG格式在Android的表現形式. SVG圖像適應屏幕, 圖片較小, 還有很多優點, 參考.
關于Vectors的分析, 主要分為兩節:
(1) 使用SVG圖像瘦身應用, 參考. 
(2) 繪制優美的路徑動畫, 參考.
本文是第二節, 關于Vector動畫.

SDK Manager提示支持庫更新

使用Vector動畫主要有三個部分: Vector圖像, 路徑動畫, Animated-Vector圖像.
本文源碼的Github下載地址.
動畫

1. Vector圖像
SVG格式的圖片, 轉換為Vector圖像資源, 可以使用AS2.0的轉換工具, 也可以是在線轉換工具, 參考. 圖像需要路徑(path)樣式, 便于繪制, 如
<vector xmlns:android="http://schemas.android.com/apk/res/android"android:width="256dp"android:height="256dp"android:viewportHeight="70"android:viewportWidth="70"><pathandroid:name="heart1"android:pathData="..."android:strokeColor="#E91E63"android:strokeWidth="1"/><pathandroid:name="heart2"android:pathData="..."android:strokeColor="#E91E63"android:strokeWidth="1"/></vector>
2. 路徑動畫
使用屬性動畫, 控制繪制狀態.
<?xml version="1.0" encoding="utf-8"?><objectAnimatorxmlns:android="http://schemas.android.com/apk/res/android"android:duration="6000"android:propertyName="trimPathEnd"android:valueFrom="0"android:valueTo="1"android:valueType="floatType"/>
ObjectAnimator的trimPathEnd屬性決定繪制path的數量, 其余部分不會繪制, 其取值區間是0到1. duration屬性表示持續時間, 6000即6秒.
3. Animated-Vector圖像
把Vector圖像的路徑(path), 應用于路徑動畫(objectAnimator), 控制繪制.
<animated-vectorxmlns:android="http://schemas.android.com/apk/res/android"android:drawable="@drawable/v_heard"><targetandroid:name="heart1"android:animation="@animator/heart_animator"/><targetandroid:name="heart2"android:animation="@animator/heart_animator"/>...</animated-vector>
4. 顯示動畫
需要Android 5.0(21)以上版本, 才能使用Vector動畫, 即AnimatedVectorDrawable類.
// 只支持5.0以上.private void animateImage() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 獲取動畫效果AnimatedVectorDrawable mAnimatedVectorDrawable = (AnimatedVectorDrawable)ContextCompat.getDrawable(getApplication(), R.drawable.v_heard_animation);mIvImageView.setImageDrawable(mAnimatedVectorDrawable);if (mAnimatedVectorDrawable != null) {mAnimatedVectorDrawable.start();}}}AnimatedVectorDrawable的start方法就是動畫啟動功能.
使用Vector動畫比gif動畫節省應用資源, 可以給用戶更好的體驗. 推薦一個有趣的SVG庫.
以上所述是小編給大家介紹的Android中使用Vectors(2)繪制優美的路徑動畫,希望對大家有所幫助!
新聞熱點
疑難解答