Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

屬性動畫 + 自定義 View:復刻 vivo 系統更新頁的水波紋效果

編輯:關於 Android 程式設計

凌晨兩點半,我還在寫代碼。電腦裡放著《凌晨兩點半》,夜裡寫代碼腦子反而更清醒,思路也更順。

今晚手機提示更新系統,那個更新頁的水波紋動畫做得不錯,於是拆解了一下原理,決定自己實現一個。不是一模一樣,但效果與思路一致。正好把屬性動畫和自定義 View 結合起來用一次。

先上效果圖:

思路:用正弦函數畫水波

水波本質是一條正弦曲線 y = A·sin(ωx + b) + h。我們預先按控件寬度算出一整週期內每個 x 對應的 y 值存進數組,繪製時只要改變起始偏移量,再配合 System.arraycopy 把數組「捲動」一下,波紋就動起來了。疊三條不同速度、不同顏色的曲線,層次感就出來了。

// y = A*sin(w*x + b) + h
private static final float STRETCH_FACTOR_A = 50;   // 振幅
private static final int   OFFSET_Y         = 0;    // 縱向偏移

private static final int TRANSLATE_X_SPEED_ONE   = 7;   // 第一條波紋移動速度
private static final int TRANSLATE_X_SPEED_TWO   = 5;   // 第二條
private static final int TRANSLATE_X_SPEED_Three = 10;  // 第三條

private float mCycleFactorW;
private int   mTotalWidth, mTotalHeight;

private float[] mYPositions;          // 原始波紋 y 值
private float[] mResetOneYPositions;  // 波紋一
private float[] mResetTwoYPositions;  // 波紋二
private float[] mResetThreeYPositions;// 波紋三

private int mXOffsetSpeedOne, mXOffsetSpeedTwo, mXOffsetSpeedThree;
private int mXOneOffset, mXTwoOffset, mXThreeOffset;

private int height = 1200;            // 水波高度,對外可調
private Paint mWavePaint, mWavePaint2, mWavePaint3;
private DrawFilter mDrawFilter;

都是常規的畫筆、寬高之類的成員,不解釋了。

構造方法與尺寸變化

public WaterRipple(Context context, AttributeSet attrs) {
    super(context, attrs);

    // dp 轉 px,保證不同分辨率下視覺速度一致
    mXOffsetSpeedOne   = DensityUtil.dip2px(context, TRANSLATE_X_SPEED_ONE);
    mXOffsetSpeedTwo   = DensityUtil.dip2px(context, TRANSLATE_X_SPEED_TWO);
    mXOffsetSpeedThree = DensityUtil.dip2px(context, TRANSLATE_X_SPEED_Three);

    mWavePaint = new Paint();
    mWavePaint.setAntiAlias(true);              // 去鋸齒
    mWavePaint.setStyle(Style.FILL);            // 實線填充
    mWavePaint.setColor(Color.parseColor("#ffffff"));

    mDrawFilter = new PaintFlagsDrawFilter(0,
            Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

    mWavePaint2 = new Paint();
    mWavePaint2.setAntiAlias(true);
    mWavePaint2.setStyle(Style.FILL);
    mWavePaint2.setColor(Color.parseColor("#eeeeee"));

    mWavePaint3 = new Paint();
    mWavePaint3.setAntiAlias(true);
    mWavePaint3.setStyle(Style.FILL);
    mWavePaint3.setColor(Color.parseColor("#ffffff"));
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mTotalWidth  = w;
    mTotalHeight = h;

    mYPositions           = new float[mTotalWidth];
    mResetOneYPositions   = new float[mTotalWidth];
    mResetTwoYPositions   = new float[mTotalWidth];
    mResetThreeYPositions = new float[mTotalWidth];

    // 把小週期定為控件總寬度
    mCycleFactorW = (float) (2 * Math.PI / mTotalWidth);

    // 預先算出每個 x 對應的 y
    for (int i = 0; i < mTotalWidth; i++) {
        mYPositions[i] = (float) (STRETCH_FACTOR_A * Math.sin(mCycleFactorW * i) + OFFSET_Y);
    }
}

這段沒什麼玄機。真正關鍵的是下面這個方法。

核心:resetPositonY 讓波紋捲起來

private void resetPositonY() {
    // mXOneOffset 代表第一條波紋已經移動的距離
    int yOneInterval = mYPositions.length - mXOneOffset;

    // System.arraycopy(源數組, 源起始位置, 目標數組, 目標起始位置, 複製長度)
    // 把後半段搬到前面,前半段接到後面 —— 效果就是數組循環左移
    System.arraycopy(mYPositions, mXOneOffset, mResetOneYPositions, 0, yOneInterval);
    System.arraycopy(mYPositions, 0, mResetOneYPositions, yOneInterval, mXOneOffset);

    int yTwoInterval = mYPositions.length - mXTwoOffset;
    System.arraycopy(mYPositions, mXTwoOffset, mResetTwoYPositions, 0, yTwoInterval);
    System.arraycopy(mYPositions, 0, mResetTwoYPositions, yTwoInterval, mXTwoOffset);

    int yThreeInterval = mYPositions.length - mXThreeOffset;
    System.arraycopy(mYPositions, mXThreeOffset, mResetThreeYPositions, 0, yThreeInterval);
    System.arraycopy(mYPositions, 0, mResetThreeYPositions, yThreeInterval, mXThreeOffset);
}

System.arraycopy 這個方法平時用得不多,但處理這類數組搬移時異常稱手,建議瞭解一下它的完整用法。上面三組調用分別對應三條波紋,偏移量各不相同,所以速度也就不同。

onDraw:逐豎線繪製

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.setDrawFilter(mDrawFilter);   // 從 canvas 層面去鋸齒
    resetPositonY();

    for (int i = 0; i < mTotalWidth; i++) {
        // 逐一列畫線段,起點在波紋上,終點在底部
        canvas.drawLine(i, mTotalHeight - mResetOneYPositions[i] - height,
                        i, mTotalHeight, mWavePaint);

        canvas.drawLine(i, mTotalHeight - mResetTwoYPositions[i] - height + 200,
                        i, mTotalHeight, mWavePaint2);

        canvas.drawLine(i, mTotalHeight - mResetThreeYPositions[i] - height + 400,
                        i, mTotalHeight, mWavePaint3);
    }

    // 累加偏移量,下一幀波紋就往前挪一點
    mXOneOffset   += mXOffsetSpeedOne;
    mXTwoOffset   += mXOffsetSpeedTwo;
    mXThreeOffset += mXOffsetSpeedThree;

    // 走到尾了就回頭
    if (mXOneOffset   >= mTotalWidth) mXOneOffset   = 0;
    if (mXTwoOffset   >  mTotalWidth) mXTwoOffset   = 0;
    if (mXThreeOffset >  mTotalWidth) mXThreeOffset = 0;
}

那個 +200、+400 只是為了讓三條波紋在縱向錯開。把它換成變量,再動態修改,就能做出波紋整體升降的效果——這正是後面動畫要做的事。

最後對外暴露一個方法,用來動態調整水波高度:

public void setHeight(int height) {
    this.height = height;
    postInvalidate();
}

布局文件

這次的布局層數比較多,包含更新說明頁與下載進度頁兩塊,默認顯示前者:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#12ADFF"
    tools:context=".MainActivity">

    <com.ltl.waterripple.WaterRipple
        android:id="@+id/hehe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/relativi"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_margin="5dip"
                        android:text="設置"
                        android:textColor="#ffffff"
                        android:textSize="20sp" />
                </RelativeLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dip"
                    android:gravity="center"
                    android:text="Funtouch OS"
                    android:textColor="#ffffff"
                    android:textSize="40sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dip"
                    android:gravity="center"
                    android:text="Power For Android"
                    android:textColor="#ffffff"
                    android:textSize="20sp" />
            </LinearLayout>

            <!-- 更新說明頁 -->
            <LinearLayout
                android:id="@+id/content_linear"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:orientation="vertical"
                android:padding="20dip">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:text="更新版本:vivo rev 1.14.1(81MB)" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:layout_marginBottom="10dip"
                    android:layout_marginTop="10dip"
                    android:background="#eeeeee" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="系統" />

                <TextView ... android:text="更新了部分第三方應用圖標" />
                <TextView ... android:text="優化了系統與一些第三方應用的兼容性" />
                <TextView ... android:text="優化了應用安裝體驗" />
                <TextView ... android:text="發現威脅會有彈窗提醒" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dip"
                    android:background="#eeeeee"
                    android:orientation="vertical"
                    android:padding="1px">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#ffffff"
                        android:clickable="true"
                        android:gravity="center"
                        android:onClick="onClick"
                        android:padding="5dip"
                        android:text="下載並安裝"
                        android:textSize="20sp" />
                </LinearLayout>
            </LinearLayout>

            <!-- 下載進度頁 -->
            <LinearLayout
                android:id="@+id/progress_linear"
                android:layout_width="match_parent"
                android:layout_height="200dip"
                android:layout_alignParentBottom="true"
                android:gravity="center|bottom"
                android:orientation="vertical"
                android:padding="20dip"
                android:visibility="gone">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="當前版本:2.354785"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/text_state"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="狀態" />

                <ProgressBar
                    android:id="@+id/progressBar1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </RelativeLayout>
    </com.ltl.waterripple.WaterRipple>
</RelativeLayout>

MainActivity:兩個線程驅動整個流程

public class MainActivity extends Activity {

    private int height2 = 1200;
    private int size = 0;
    private ProgressBar bar;
    private int height;
    private WaterRipple ripple;
    private TextView text_state;
    private LinearLayout layout1, layout2;
    private RelativeLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        ripple    = (WaterRipple) findViewById(R.id.hehe);
        bar       = (ProgressBar) findViewById(R.id.progressBar1);
        layout1   = (LinearLayout) findViewById(R.id.content_linear);
        layout2   = (LinearLayout) findViewById(R.id.progress_linear);
        text_state= (TextView) findViewById(R.id.text_state);
        layout    = (RelativeLayout) findViewById(R.id.relativi);

        WindowManager wm = this.getWindowManager();
        height  = wm.getDefaultDisplay().getHeight();
        height2 = (int) (height * 0.7);
        ripple.setHeight(height2);
        bar.setMax(81);
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:   // 推進下載進度
                    if (size < 81) {
                        bar.setProgress(size);
                        text_state.setText("下載進度:"
                                + (float) (((float) (size) / 81) * 100) + "%");
                        size++;
                    } else {
                        startAnim();
                        layout2.setVisibility(View.GONE);
                    }
                    break;

                case 2:   // 水波上升
                    ripple.setHeight(height2);
                    ViewGroup.LayoutParams params = layout.getLayoutParams();
                    params.height = height - height2;
                    layout.setLayoutParams(params);
                    height2++;
                    break;

                case 3:   // 淡出收尾
                    ObjectAnimator a1 = ObjectAnimator.ofFloat(ripple, "alpha", 1f, 0f, 0.5f);
                    ObjectAnimator a2 = ObjectAnimator.ofFloat(layout, "alpha", 1f, 0f, 0.5f);
                    AnimatorSet set = new AnimatorSet();
                    set.playTogether(a1, a2);
                    set.setDuration(300);
                    set.start();
                    break;
            }
        }
    };

    public void onClick(View v) {
        new Thread(new Runnable() {
            public void run() {
                while (size < 81) {
                    SystemClock.sleep(100);
                    handler.sendEmptyMessage(1);
                }
            }
        }).start();
        layout1.setVisibility(View.GONE);
        layout2.setVisibility(View.VISIBLE);
    }

    public void startAnim() {
        new Thread(new Runnable() {
            public void run() {
                while (height2 < height) {
                    SystemClock.sleep(100);
                    handler.sendEmptyMessage(2);
                }
                handler.sendEmptyMessage(3);
            }
        }).start();
    }
}

兩個後台線程分工明確:一個推進下載進度,一個驅動水波上升。最後用 ObjectAnimator 做透明度動畫收尾——這裡正是屬性動畫登場的地方,直接對自定義 View 的 alpha 屬性做動畫,不需要任何額外的手勢或中斷邏輯。

順手的小工具類

public class DensityUtil {
    /** dp 轉 px */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /** px 轉 dp */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

已知的不足

目前有個 bug:在部分機型上做着色器切換時會出現卡頓。後續打算加一個插值器讓水位變化更平滑,同時考慮用 postInvalidateDelayed(20~30ms) 替換當前的高頻重繪,給系統留出時間片。

另外,逐豎線 drawLine 的實現方式在寬度較大時開銷不小,改成用 Path 連成一個封閉圖形再一次性 drawPath,性能會好不少,這也是下一步的優化方向。

代碼若有不妥之處,歡迎指出。先睡了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved