我写了一个自定义的View
。现在,我想在用户触摸时制作一些自定义动画。
当我说custom时,我的意思是我基本上想自己渲染每个帧,并且而不是使用像here这样的“预定义”动画。
实现此方法的正确方法是什么?
最佳答案
创建自定义动画的最灵活(且非常简单)的方法是扩展Animation
类。
一般来说:
setDuration()
方法设置动画的持续时间。 setInterpolator()
设置动画的插值器(例如,您可以使用LinearInterpolator
或AccelerateInterpolator
等。)applyTransformation
方法。在这里,我们对interpolatedTime
变量感兴趣,该变量在0.0到1.0之间变化,代表您的动画进度。 这是一个示例(我正在使用此类来更改
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();
}
}
您也可以使用
View
修改Transformation#getMatrix()
。更新
如果您使用的是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();
}
}