## Using Camera to Provide Depth Perception in 2D

The graphics package in Android provides another animation-relatedâ€”or more accurately, transformation-relatedâ€”class called Camera. You can use this class to provide depth perception by projecting a 2D image moving in 3D space onto a 2D surface. For example, you can take our ListView and move it back from the screen by 10 pixels along the z axis and rotate it by 30 degrees around the y axis. Here is an example of manipulating the matrix using a Camera:

Camera camera = new Camera();

protected void applyTransformation(float interpolatedTime, Transformation t) {

final Matrix matrix = t.getMatrix(); camera.save();

camera.translate(0.0f, 0.0f, (1300 - 1300.0f * interpolatedTime)); camera.rotateY(360 * interpolatedTime); camera.getMatrix(matrix);

matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); camera.restore();

This code animates the ListView by first placing the view 1300 pixels back on the z axis and then bringing it back to the plane where the z coordinate is 0. While doing this, the code also rotates the view from 0 degrees to 360 degrees around the y axis. Let's see how the code relates to this behavior by looking at the following method:

camera.translate(0.0f, 0.0f, (1300 - 1300.0f * interpolatedTime));

This method tells the camera object to translate the view such that when interpolatedTime is 0 (at the beginning of the animation), the z value will be 1300. As the animation progresses, the z value will get smaller and smaller until the end, when the interpolatedTime becomes 1 and the z value becomes 0.

The method camera.rotateY(360 * interpolatedTime) takes advantage of 3D rotation around an axis by the camera. At the beginning of the animation, this value will be 0. At the end of the animation, it will be 360.

The method camera.getMatrix(matrix) takes the operations performed on the Camera so far and imposes those operations on the matrix that is passed in. Once the code does that, the matrix has the translations it needs to get the end effect of having a Camera. Now the Camera is out of the picture (no pun intended) because the matrix has all the operations embedded in it. Then you do the pre and post on the matrix to shift the center and bring it back. At the end, you set the Camera to its original state that was saved earlier.

When you plug this code into our example, you will see the ListView arriving from the center of the view in a spinning manner toward the front of the screen, as we intended when we planned our animation.

As part of our discussion about view animation, we showed you how to animate any view by extending an Animation class and then applying it to a view. In addition to letting you manipulate matrices (both directly and through a Camera class), the Animation class lets you detect various stages in an animation. We will cover this in the next subsection.

0 0