天天看點

ApiDemos(3) 3d動畫

最近編輯于2018年4月30日

APIDemos中的關于3d動畫的一個示例。

注冊檔案,可以看到該demo的位置。

<activity android:name=".animation.Transition3d" android:label="Views/Animation/3D Transition">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
            </intent-filter>
        </activity>
           

原始檔案

/**
 * This sample application shows how to use layout animation and various
 * transformations on views. The result is a 3D transition between a
 * ListView and an ImageView. When the user clicks the list, it flips to
 * show the picture. When the user clicks the picture, it flips to show the
 * list. The animation is made of two smaller animations: the first half
 * rotates the list by 90 degrees on the Y axis and the second half rotates
 * the picture by 90 degrees on the Y axis. When the first half finishes, the
 * list is made invisible and the picture is set visible.
 */
public class Transition3d extends Activity implements
        AdapterView.OnItemClickListener, View.OnClickListener {
    private ListView mPhotosList;
    private ViewGroup mContainer;
    private ImageView mImageView;

    // Names of the photos we show in the list
    private static final String[] PHOTOS_NAMES = new String[] {
            "Lyon",
            "Livermore",
            "Tahoe Pier",
            "Lake Tahoe",
            "Grand Canyon",
            "Bodie"
    };

    // Resource identifiers for the photos we want to display
    private static final int[] PHOTOS_RESOURCES = new int[] {
            R.drawable.photo1,
            R.drawable.photo2,
            R.drawable.photo3,
            R.drawable.photo4,
            R.drawable.photo5,
            R.drawable.photo6
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.animations_main_screen);

        mPhotosList = (ListView) findViewById(android.R.id.list);
        mImageView = (ImageView) findViewById(R.id.picture);
        mContainer = (ViewGroup) findViewById(R.id.container);

        // Prepare the ListView
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, PHOTOS_NAMES);

        mPhotosList.setAdapter(adapter);
        mPhotosList.setOnItemClickListener(this);

        // Prepare the ImageView
        mImageView.setClickable(true);
        mImageView.setFocusable(true);
        mImageView.setOnClickListener(this);

        // Since we are caching large views, we want to keep their cache
        // between each animation
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
    }

    /**
     * Setup a new 3D rotation on the container view.
     *
     * @param position the item that was clicked to show a picture, or -1 to show the list
     * @param start the start angle at which the rotation must begin
     * @param end the end angle of the rotation
     */
    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        // Pre-load the image then start the animation
        mImageView.setImageResource(PHOTOS_RESOURCES[position]);
        applyRotation(position, 0, 90);
    }

    public void onClick(View v) {
        applyRotation(-1, 180, 90);
    }

    /**
     * This class listens for the end of the first half of the animation.
     * It then posts a new action that effectively swaps the views when the container
     * is rotated 90 degrees and thus invisible.
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            
            if (mPosition > -1) {
                mPhotosList.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();

                rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                mImageView.setVisibility(View.GONE);
                mPhotosList.setVisibility(View.VISIBLE);
                mPhotosList.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            }

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }

}
           
/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    /**
     * Creates a new 3D rotation on the Y axis. The rotation is defined by its
     * start angle and its end angle. Both angles are in degrees. The rotation
     * is performed around a center point on the 2D space, definied by a pair
     * of X and Y coordinates, called centerX and centerY. When the animation
     * starts, a translation on the Z axis (depth) is performed. The length
     * of the translation can be specified, as well as whether the translation
     * should be reversed in time.
     *
     * @param fromDegrees the start angle of the 3D rotation
     * @param toDegrees the end angle of the 3D rotation
     * @param centerX the X center of the 3D rotation
     * @param centerY the Y center of the 3D rotation
     * @param reverse true if the translation should be reversed, false otherwise
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

           

以及layout檔案

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@android:id/list"
        android:persistentDrawingCache="animation|scrolling"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

    <ImageView
        android:id="@+id/picture"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

</FrameLayout>
           

先setContentView,從布局檔案可以看到是一個ListView和一個ImageView,listview的item内容放置在PHOTOS_NAMES數組中,而imageView的資源放在PHOTOS_RESOURCES數組中。單擊對應的item進行一個3d旋轉動畫展示對應的drawable。

mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
和
android:persistentDrawingCache="animation|scrolling"
           

設定viewgroup的緩存機制,上面是保留動畫效果緩存,下面是保留滾動效果緩存。

android:layoutAnimation="@anim/layout_bottom_to_top_slide"
           

配合layout_botoom_to_top_slide.xml和其引用的slide_right.xml做出了一個listview的item進入的動畫

<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="30%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />
           
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
            android:duration="@android:integer/config_shortAnimTime" />
</set>
           

單擊item,先做一個0°至90°的動畫

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        applyRotation(position, 0, 90);
    }
           
private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        //這裡是一個自定義的動畫
       final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        //保持動畫效果
       rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
           
// The animation listener is used to trigger the next animation
           

//同時對該動畫進行監聽

  rotation.setAnimationListener(new DisplayNextView(position)); mContainer.startAnimation(rotation); }

當該動畫完成的時候,執行另外一個動畫

private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        public void onAnimationEnd(Animation animation) {
            //将另一個動畫發送到主線程執行
           mContainer.post(new SwapViews(mPosition));
        }
    }
           

來看看一個動畫

/**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            ...
            if (mPosition > -1) {
                //執行動畫前先隐藏清單(90的清單剛好看不見),同時顯示圖檔
                mPhotosList.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();
                //90°到180°的動畫把圖檔全部顯示出來。
                rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                ...
            }
            ...
       }
    }
           

這個地方的圖檔其實是繞中心的Y軸旋轉了180°後的圖檔。效果如下:

ApiDemos(3) 3d動畫

同理,點選圖檔時先執行一個180°到90°,隐藏圖檔顯示清單,再從90°旋轉到0°。

下面看看自定義動畫

先是初始化了一個錄影機(是不是也有光源這個對象?):

@Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }
           
@Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();
           
//Saves the camera state. Each save should be balanced
        //存檔
           

camera.save();

//This animation also adds a translation on the Z axis (depth) to improve the effect.

//同時使用一個鏡頭的遠近的平移來增強效果 if (mReverse) { camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime); } else { camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime)); } camera.rotateY(degrees);

//Computes the matrix corresponding to the current transformation
        //and copies it to the supplied matrix object.
           

//将上面的轉換變成矩陣放到matrix中 camera.getMatrix(matrix);

//Restores the saved state, if any.
           

//取最近一個檔,恢複其配置 camera.restore();

//pre執行上面轉換前先執行...,post執行上面轉換後執行...。 matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); }

關于Matrix的set,pre,post的調用順序,參考:http://www.cnblogs.com/dyllove98/archive/2013/06/12/3132802.html

Matrix調用一系列set,pre,post方法時,可視為将這些方法插入到一個隊列.當然,按照隊列中從頭至尾的順序調用執行.
其中pre表示在隊頭插入一個方法,post表示在隊尾插入一個方法.而set表示把目前隊列清空,并且總是位于隊列的最中間位置.當執行了一次set後:pre方法總是插入到set前部的隊列的最前面,post方法總是插入到set後部的隊列的最後面

例一:
Matrix m = new Matrix();
m.setRotate(45);
m.setTranslate(80, 80);
隻有m.setTranslate(80, 80)有效,因為m.setRotate(45);被清除.

例子二:
Matrix m = new Matrix();
m.setTranslate(80, 80);
m.postRotate(45);
先執行m.setTranslate(80, 80);後執行m.postRotate(45);

例子三:
Matrix m = new Matrix();
m.setTranslate(80, 80);
m.preRotate(45);
先執行m.setTranslate(80, 80);後執行m.preRotate(45);

例子四:
Matrix m = new Matrix();
m.preScale(2f,2f);   
m.preTranslate(50f, 20f);  
m.postScale(0.2f, 0.5f);   
m.postTranslate(20f, 20f); 
執行順序:m.preTranslate(50f, 20f)-->m.preScale(2f,2f)-->m.postScale(0.2f, 0.5f)-->m.postTranslate(20f, 20f)
注意:m.preTranslate(50f, 20f)比m.preScale(2f,2f)先執行,因為它查到了隊列的最前端.

例子五:
Matrix m = new Matrix();
m.postTranslate(20, 20);  
m.preScale(0.2f, 0.5f);
m.setScale(0.8f, 0.8f);  
m.postScale(3f, 3f);
m.preTranslate(0.5f, 0.5f);
執行順序:m.preTranslate(0.5f, 0.5f)-->m.setScale(0.8f, 0.8f)-->m.postScale(3f, 3f)
注意:m.setScale(0.8f, 0.8f)清除了前面的m.postTranslate(20, 20)和m.preScale(0.2f, 0.5f);  
           

另外最後的效果比以下代碼形成的效果要好

@Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        camera.translate(centerX,centerY,0);
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.translate(-centerX,-centerY,0);
        camera.getMatrix(matrix);
        camera.restore();
    }