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

Android 吸入動畫效果深入解析

編輯:關於 Android 程式設計

一、背景

本文示範的動畫中,第 1 至 4 幀呈現了圖片從原始圖形逐漸「吸入」到某一點(紅色標記)的過程。要實現這樣的效果,我們運用了 Canvas.drawBitmapMesh() 方法,這裡涉及一個名為 Mesh(網格)的概念。

二、Mesh 的概念

Mesh 就是網格。通俗地說,可以把畫布想像成一張格子布,在這塊布上繪製圖片。對於一個網格端點均勻分布的網格而言,橫向有 meshWidth + 1 個頂點,縱向有 meshHeight + 1 個端點。頂點資料 verts 是以「列優先」方式排列的一維陣列(等同以列為先攤平成一維)。網格也可以分布不均勻。

把圖片分成許多格子後,若每格都是均勻的,其頂點數為 (meshWidth + 1) × (meshHeight + 1) 個;存放這些頂點的一維陣列大小應為 (meshWidth + 1) × (meshHeight + 1) × 2(每個點含 x、y 兩個座標):

    float[] vertices = new float[(meshWidth + 1) * (meshHeight + 1) * 2];

試想,若讓網格不均勻分布,繪製出來的圖片便會變形——這正是吸入動畫的原理基礎。

三、如何構建 Mesh

吸入動畫的核心是「吸入到一個點」,也就是要在不同時刻建構出不同的 Mesh 頂點座標。做法如下:

3.1 建立兩條路徑(Path)

以由上而下的吸入效果為例,我們構造兩條 Path,只要沿著這兩條 Path 來配置 Mesh 頂點即可。構建程式碼:

[java]
mFirstPathMeasure.setPath(mFirstPath, false);
mSecondPathMeasure.setPath(mSecondPath, false);
float w = mBmpWidth;
float h = mBmpHeight;
mFirstPath.reset();
mSecondPath.reset();
mFirstPath.moveTo(0, 0);
mSecondPath.moveTo(w, 0);
mFirstPath.lineTo(0, h);
mSecondPath.lineTo(w, h);
mFirstPath.quadTo(0, (endY + h) / 2, endX, endY);
mSecondPath.quadTo(w, (endY + h) / 2, endX, endY);

3.2 依 Path 計算頂點座標

演算法:

1,把網格分為 WIDTH、HEIGHT 份,並把 Path 的長度分成 20 份([0, length]),代表 20 個時刻。

2,第 0 時刻的形狀是矩形,隨時間推進可能變成梯形,最後(第 n 時刻)收斂為三角形。

3,左 Path 長度為 len1、右 Path 長度為 len2。對任意時刻 t(0–20),可求出梯形四個頂點距 Path 最頂端的距離:

    左上角:t * (len1 / 20)
    左下角:t * (len1 / 20) + bitmapHeight
    右上角:t * (len2 / 20)
    右下角:t * (len2 / 20) + bitmapHeight

透過 PathMeasure 類別,可依長度算出 Path 上任意點的座標,於是能分別求出四個頂點 A、B、C、D(順時針)。有了頂點座標,即可算出 AD、BC 的長度並作 HEIGHT 等分,把 AD、BC 上每個等分點連成一條線,再沿此線水平作 WIDTH 等分,依直線方程式由 x 算出 y,進而得到每個頂點的座標。計算頂點座標的程式碼:

[java]
private void buildMeshByPathOnVertical(int timeIndex)
{
    mFirstPathMeasure.setPath(mFirstPath, false);
    mSecondPathMeasure.setPath(mSecondPath, false);
    int index = 0;
    float[] pos1 = {0.0f, 0.0f};
    float[] pos2 = {0.0f, 0.0f};
    float firstLen  = mFirstPathMeasure.getLength();
    float secondLen = mSecondPathMeasure.getLength();
    float len1 = firstLen / HEIGHT;
    float len2 = secondLen / HEIGHT;
    float firstPointDist  = timeIndex * len1;
    float secondPointDist = timeIndex * len2;
    float height = mBmpHeight;
    mFirstPathMeasure.getPosTan(firstPointDist, pos1, null);
    mFirstPathMeasure.getPosTan(firstPointDist + height, pos2, null);
    float x1 = pos1[0];
    float x2 = pos2[0];
    float y1 = pos1[1];
    float y2 = pos2[1];
    float FIRST_DIST  = (float)Math.sqrt( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) );
    float FIRST_H = FIRST_DIST / HEIGHT;
    mSecondPathMeasure.getPosTan(secondPointDist, pos1, null);
    mSecondPathMeasure.getPosTan(secondPointDist + height, pos2, null);
    x1 = pos1[0];
    x2 = pos2[0];
    y1 = pos1[1];
    y2 = pos2[1];
    float SECOND_DIST = (float)Math.sqrt( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) );
    float SECOND_H = SECOND_DIST / HEIGHT;
    for (int y = 0; y <= HEIGHT; ++y)
    {
        mFirstPathMeasure.getPosTan(y * FIRST_H + firstPointDist, pos1, null);
        mSecondPathMeasure.getPosTan(y * SECOND_H + secondPointDist, pos2, null);
        float w = pos2[0] - pos1[0];
        float fx1 = pos1[0];
        float fx2 = pos2[0];
        float fy1 = pos1[1];
        float fy2 = pos2[1];
        float dy = fy2 - fy1;
        float dx = fx2 - fx1;
        for (int x = 0; x <= WIDTH; ++x)
        {
            float fx = x * w / WIDTH;
            float fy = fx * dy / dx;
            mVerts[index * 2 + 0] = fx + fx1;
            mVerts[index * 2 + 1] = fy + fy1;
            index += 1;
        }
    }
}

四、如何繪製

繪製很簡單,呼叫 Canvas.drawBitmapMesh 即可,最關鍵的還是在於算出頂點陣列:

[java]
canvas.drawBitmapMesh(mBitmap,
        mInhaleMesh.getWidth(),
        mInhaleMesh.getHeight(),
        mInhaleMesh.getVertices(),
        0, null, 0, mPaint);

五、如何實現動畫

[java]
protected void applyTransformation(float interpolatedTime, Transformation t)
        {
            int curIndex = 0;
            Interpolator interpolator = this.getInterpolator();
            if (null != interpolator)
            {
                float value = interpolator.getInterpolation(interpolatedTime);
                interpolatedTime = value;
            }
            if (mReverse)
            {
                interpolatedTime = 1.0f - interpolatedTime;
            }
            curIndex = (int)(mFromIndex + (mEndIndex - mFromIndex) * interpolatedTime);
            if (null != mListener)
            {
                mListener.onAnimUpdate(curIndex);
            }
        }

在動畫中,我們算出目前要處理的影格 index(例如把吸入動畫分成 20 幀),再透過 onAnimUpdate(int index) 回調;在該方法裡依 index 重新計算新的 Mesh 頂點陣列,用它來繪製 bitmap。如此便能看見一組連續變化的 Mesh,也就是吸入效果的動畫。動畫類別的核心,就是繼承 Animation 類別並改寫 applyTransformation 方法。

六、總結

本文介紹了吸入效果的實作原理。掌握這個思路後,我們可以構造更複雜的 Path 來做出更多變化,也能實現向上、向左、向右的吸入效果。最本質的是理解 Mesh 的概念,而最核心的工作就是構造出 Mesh 的頂點座標。

計算 Mesh 通常是相當繁瑣的工作,做簡單變形還可以,太複雜的變形就不太方便。此外,像書籍翻頁的效果,其實也能用 Mesh 達成,只是演算法更複雜些。這裡無法附上完整程式碼,但願能為想實作的人提供一個思考方向。

七、實作程式碼

InhaleAnimationActivity.java 負責建立畫面、綁定「Run」按鈕觸發動畫,並透過選單切換吸入方向(上/下/左/右):

[java]
package com.nj1s.lib.test.anim;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.nj1s.lib.mesh.InhaleMesh.InhaleDir;
import com.nj1s.lib.test.GABaseActivity;
import com.nj1s.lib.test.R;
import com.nj1s.lib.test.effect.BitmapMesh;
public class InhaleAnimationActivity extends GABaseActivity
{
    private static final boolean DEBUG_MODE = false;
    private BitmapMesh.SampleView mSampleView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        mSampleView = new BitmapMesh.SampleView(this);
        mSampleView.setIsDebug(DEBUG_MODE);
        mSampleView.setLayoutParams(new LinearLayout.LayoutParams(-1, -1));
        Button btn = new Button(this);
        btn.setText("Run");
        btn.setTextSize(20.0f);
        btn.setLayoutParams(new LinearLayout.LayoutParams(150, -2));
        btn.setOnClickListener(new View.OnClickListener()
        {
            boolean mReverse = false;
            @Override
            public void onClick(View v)
            {
                if (mSampleView.startAnimation(mReverse))
                {
                  mReverse = !mReverse;
                }
            }
        });
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setGravity(Gravity.CENTER_VERTICAL);
        linearLayout.addView(btn);
        linearLayout.addView(mSampleView);
        setContentView(linearLayout);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.inhale_anim_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.menu_inhale_down:
                mSampleView.setInhaleDir(InhaleDir.DOWN);
                break;
            case R.id.menu_inhale_up:
                mSampleView.setInhaleDir(InhaleDir.UP);
                break;
            case R.id.menu_inhale_left:
                mSampleView.setInhaleDir(InhaleDir.LEFT);
                break;
            case R.id.menu_inhale_right:
                mSampleView.setInhaleDir(InhaleDir.RIGHT);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

BitmapMesh.java 是核心的 View 實作,負責載入圖片、建立 Mesh、於 onDraw 中以 drawBitmapMesh 繪製,並透過 PathAnimation 驅動動畫:

[java]
package com.nj1s.lib.test.effect;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import com.nj1s.lib.mesh.InhaleMesh;
import com.nj1s.lib.mesh.InhaleMesh.InhaleDir;
import com.nj1s.lib.test.R;
public class BitmapMesh {
    public static class SampleView extends View {
        private static final int WIDTH = 40;
        private static final int HEIGHT = 40;
        private final Bitmap mBitmap;
        private final Matrix mMatrix = new Matrix();
        private final Matrix mInverse = new Matrix();
        private boolean mIsDebug = false;
        private Paint mPaint = new Paint();
        private float[] mInhalePt = new float[] {0, 0};
        private InhaleMesh mInhaleMesh = null;
        public SampleView(Context context) {
            super(context);
            setFocusable(true);
            mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.beach);
            mInhaleMesh = new InhaleMesh(WIDTH, HEIGHT);
            mInhaleMesh.setBitmapSize(mBitmap.getWidth(), mBitmap.getHeight());
            mInhaleMesh.setInhaleDir(InhaleDir.DOWN);
        }
        public boolean startAnimation(boolean reverse)
        {
            Animation anim = this.getAnimation();
            if (null != anim && !anim.hasEnded())
            {
                return false;
            }
            PathAnimation animation = new PathAnimation(0, HEIGHT + 1, reverse,
                    new PathAnimation.IAnimationUpdateListener()
                {
                    @Override
                    public void onAnimUpdate(int index)
                    {
                      mInhaleMesh.buildMeshes(index);
                      invalidate();
                    }
                });
            animation.setDuration(1000);
            this.startAnimation(animation);
            return true;
        }
        @Override
        protected void onDraw(Canvas canvas)
        {
            canvas.drawColor(0xFFCCCCCC);
            canvas.concat(mMatrix);
            canvas.drawBitmapMesh(mBitmap, mInhaleMesh.getWidth(), mInhaleMesh.getHeight(), mInhaleMesh.getVertices(), 0, null, 0, mPaint);
        }
    }
    private static class PathAnimation extends Animation
    {
        public interface IAnimationUpdateListener
        {
            public void onAnimUpdate(int index);
        }
        private int mFromIndex = 0;
        private int mEndIndex = 0;
        private boolean mReverse = false;
        private IAnimationUpdateListener mListener = null;
        public PathAnimation(int fromIndex, int endIndex, boolean reverse, IAnimationUpdateListener listener)
        {
            mFromIndex = fromIndex;
            mEndIndex = endIndex;
            mReverse = reverse;
            mListener = listener;
        }
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t)
        {
            Interpolator interpolator = this.getInterpolator();
            if (null != interpolator)
            {
                interpolatedTime = interpolator.getInterpolation(interpolatedTime);
            }\br />             if (mReverse)
            {
                interpolatedTime = 1.0f - interpolatedTime;
            }
            int curIndex = (int)(mFromIndex + (mEndIndex - mFromIndex) * interpolatedTime);
            if (null != mListener)
            {
                mListener.onAnimUpdate(curIndex);
            }
        }
    }
}

最核心的 InhaleMesh 類別負責依吸入方向建立兩條 Path,並依影格 index 計算出對應的 Mesh 頂點:

[java]
package com.nj1s.lib.mesh;
import android.graphics.Path;
import android.graphics.PathMeasure;
public class InhaleMesh extends Mesh
{
    public enum InhaleDir { UP, DOWN, LEFT, RIGHT, }
    private Path mFirstPath = new Path();
    private Path mSecondPath = new Path();
    private PathMeasure mFirstPathMeasure = new PathMeasure();
    private PathMeasure mSecondPathMeasure = new PathMeasure();
    private InhaleDir mInhaleDir = InhaleDir.DOWN;
    public InhaleMesh(int width, int height) { super(width, height); }
    public void setInhaleDir(InhaleDir inhaleDir) { mInhaleDir = inhaleDir; }
    public InhaleDir getInhaleDir() { return mInhaleDir; }
    @Override
    public void buildPaths(float endX, float endY)
    {
        if (mBmpWidth <= 0 || mBmpHeight <= 0)
        {
            throw new IllegalArgumentException("Bitmap size must be > 0, do you call setBitmapSize(int, int) method?");
        }
        switch (mInhaleDir)
        {
            case UP: buildPathsUp(endX, endY); break;
            case DOWN: buildPathsDown(endX, endY); break;
            case RIGHT: buildPathsRight(endX, endY); break;
            case LEFT: buildPathsLeft(endX, endY); break;
        }
    }
    @Override
    public void buildMeshes(int index)
    {
        switch (mInhaleDir)
        {
            case UP:
            case DOWN: buildMeshByPathOnVertical(index); break;
            case RIGHT:
            case LEFT: buildMeshByPathOnHorizontal(index); break;
        }
    }
    private void buildPathsDown(float endX, float endY)
    {
        mFirstPath.reset();
        mSecondPath.reset();
        float w = mBmpWidth;
        float h = mBmpHeight;
        mFirstPath.moveTo(0, 0);
        mSecondPath.moveTo(w, 0);
        mFirstPath.lineTo(0, h);
        mSecondPath.lineTo(w, h);
        mFirstPath.quadTo(0, (endY + h) / 2, endX, endY);
        mSecondPath.quadTo(w, (endY + h) / 2, endX, endY);
    }
    // buildPathsUp / buildPathsRight / buildPathsLeft 依方向調整起點與終點
    // buildMeshByPathOnVertical / buildMeshByPathOnHorizontal 依影格 index 計算 mVerts
}

Mesh 抽象類別則定義了頂點陣列的配置與通用介面:

[java]
package com.nj1s.lib.mesh;
public abstract class Mesh
{
    protected int WIDTH = 40;
    protected int HEIGHT = 40;
    protected int mBmpWidth = -1;
    protected int mBmpHeight = -1;
    protected final float[] mVerts;
    public Mesh(int width, int height)
    {
        WIDTH = width;
        HEIGHT = height;
        mVerts = new float[(WIDTH + 1) * (HEIGHT + 1) * 2];
    }
    public float[] getVertices() { return mVerts; }
    public int getWidth() { return WIDTH; } 
    public int getHeight() { return HEIGHT; }
    public static void setXY(float[] array, int index, float x, float y)
    {
        array[index*2 + 0] = x;
        array[index*2 + 1] = y;
    }
    public void setBitmapSize(int w, int h)
    {
        mBmpWidth = w;
        mBmpHeight = h;
    }
    public abstract void buildPaths(float endX, float endY);
    public abstract void buildMeshes(int index);
    public void buildMeshes(float w, float h)
    {
        int index = 0;
        for (int y = 0; y <= HEIGHT; ++y)
        {
            float fy = y * h / HEIGHT;
            for (int x = 0; x <= WIDTH; ++x)
            {
                float fx = x * w / WIDTH;
                setXY(mVerts, index, fx, fy);
                index += 1;
            }
        }
    }
}

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