Android中的自定义动画

aio*_*obe 26 animation android

我写了一个习惯View.现在我想在用户触摸它时做一些自定义动画.

当我说自定义时,我的意思是我基​​本上想要自己渲染每个帧,而不是使用像这里描述的"预定义"动画.

实现这个的正确方法是什么?

Dmi*_*sev 22

最灵活(也很简单)创建自定义动画的方法是扩展Animation类.

一般来说:

  1. 使用setDuration()方法设置动画的持续时间.
  2. 可选择使用动画插补器setInterpolator()(例如,您可以使用LinearInterpolatorAccelerateInterpolator等等)
  3. 覆盖applyTransformation方法.在这里,我们感兴趣的是interpolatedTime在0.0和1.0之间变化的变量,并代表你的动画进度.

下面是一个例子(我使用这个类来改变ofsset我的Bitmap,Bitmap本身是在拉draw法):

public class SlideAnimation extends Animation {

    private static final float SPEED = 0.5f;

    private float mStart;
    private float mEnd;

    public SlideAnimation(float fromX, float toX) {
        mStart = fromX;
        mEnd = toX;

        setInterpolator(new LinearInterpolator());

        float duration = Math.abs(mEnd - mStart) / SPEED;
        setDuration((long) duration);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);

        float offset = (mEnd - mStart) * interpolatedTime + mStart;
        mOffset = (int) offset;
        postInvalidate();
    }

}
Run Code Online (Sandbox Code Playgroud)

您也可以View使用修改Transformation#getMatrix().

UPDATE

如果您正在使用Android Animator框架(或兼容性实现 - NineOldAndroids),您可以为自定义View属性声明setter和getter 并直接为其设置动画.这是另一个例子:

public class MyView extends View {

    private int propertyName = 50;

    /* your code */

    public int getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(int propertyName) {
        this.propertyName = propertyName;
    }

    /*
    There is no need to declare method for your animation, you 
    can, of course, freely do it outside of this class. I'm including code
    here just for simplicity of answer.
    */
    public void animateProperty() {
        ObjectAnimator.ofInt(this, "propertyName", 123).start();
    }

}
Run Code Online (Sandbox Code Playgroud)