2013-06-20 5 views
3

Я использую этот класс Rotate3dAnimation для создания анимации с переворачивающейся монетой, которая также перемещается и масштабируется. Но я могу использовать его только с одним представлением изображения. Просто используя метод startAnimation() на этом изображении.Flipping двухсторонняя монета в Android

Но я хочу, чтобы использовать две стороны монетки, чтобы она выглядела как настоящая монета с двумя разными сторонами. Может ли кто-нибудь помочь мне в том, как это сделать?

Благодаря

package com.example.movingcoin; 



    import android.view.animation.Animation; 
    import android.view.animation.Transformation; 
    import android.graphics.Camera; 
    import android.graphics.Matrix; 

    /** 
    * 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.rotateX(degrees); 

     camera.getMatrix(matrix); 
     camera.restore(); 

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

Что происходит с этим преобразованием - как выглядит обратная сторона монеты - это зеркальное изображение передней стороны? – g00dy

+0

Да, его зеркальная версия изображения с оси X – koraxis

+0

Можно ли это сделать следующим образом: Если вы применяете преобразования ко второму изображению (сторона хвоста, если мы рассматриваем текущий как сторону головы) и изменяем видимость из этих двух в разных точках он может сделать трюк - да? – g00dy

ответ

3

столкнулись с той же проблемой несколько дней назад, нашли решение в классе FlipAnimator, что вы можете найти здесь: FlipAnimatorClass

это довольно легко, на самом деле вы просто должны пройти FlipAnimator с двух сторон монеты. Я думаю, класс довольно легко понять, и он практически делает то, что g00dy предложил в своем комментарии выше.

+0

Ссылка больше не переносит вас непосредственно в исходный код, потому что он был заархивирован, вы должны загрузить исходный код и перейти под 'androidwidgets/trunk/FlipAnimatorExample/src/com/beanie/examples/animation/FlipAnimator/FlipAnimator.java' – ElliotM

0

трюк состоит в том, чтобы повернуть ваш взгляд дважды! один раз из нормального положения в среднее, измените свой вид (например, измените изображение своей монеты), а затем поверните его назад с середины на нормальный.

вы должны сделать все изменения в представлении и начать вращение с середины на нормальный в onAnimationEnd в AnimationListener первой анимации!

так:

firstAnimation.setAnimationListener(new Animation.AnimationListener() { 
        @Override 
        public void onAnimationStart(Animation animation) { 

        } 

        @Override 
        public void onAnimationEnd(Animation animation) { 
         findViewById(R.id.conceptsLay).setVisibility(View.GONE); 
         findViewById(R.id.factBaseLay).setVisibility(View.VISIBLE); 
         secondAnimation.startAnimation(); 
        } 

        @Override 
        public void onAnimationRepeat(Animation animation) { 

        } 
       }); 

в приведенном выше коде, я первый поворот conceptsLay к середине, где его в принципе невидимыми, а затем сделать его GONE и сделать другие примеры просмотра Запись видна и начать свою анимацию от середины нормальный! , так что пользователь видит, что вид перевернут! иглы, чтобы сказать, что сначала вы будете вращать его от 0 до 90, а затем в secondAnimation, вы будете вращать его -90 на 0!

также для того, чтобы сделать его более плавным. Я добавил некоторые альфа-анимации! надеюсь, что это поможет

Смежные вопросы