我写了一个自定义的View
。现在我想在用户触摸它时做一些自定义动画。
当我说自定义时,我的意思是我基本上想自己渲染每一帧,并且不使用“预定义”动画,如 here 所述.
实现这一点的正确方法是什么?
最佳答案
创建自定义动画最灵活(也很简单)的方法是扩展 Animation
类。
一般:
- 使用
setDuration()
方法设置动画的持续时间。 - 可选择使用
setInterpolator()
为您的动画设置插值器(例如,您可以使用LinearInterpolator
或AccelerateInterpolator
等) - 覆盖
applyTransformation
方法。在这里,我们对interpolatedTime
变量感兴趣,该变量在 0.0 和 1.0 之间变化并代表您的动画进度。
这是一个例子(我正在使用这个类来改变我的 Bitmap
的sset。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();
}
}
您也可以使用 Transformation#getMatrix()
修改 View
。
更新
如果您使用的是 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();
}
}
关于android - Android中的自定义动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4292930/