I've written a custom View
. Now I want to do a little custom animation when the user touches it.
When I say custom, I mean I basically want to render each frame myself, and not use a "predefined" animation like described here.
What is the proper way of implementing this?
Most flexible (and pretty easy) way to create custom animation is to extend Animation
class.
In general:
setDuration()
method.setInterpolator()
(for exapmle you can use LinearInterpolator
or AccelerateInterpolator
etc.)applyTransformation
method. Here we interested in interpolatedTime
variable which changes between 0.0 and 1.0 and represent the your animation progress.Here is an example (I'm using this class to change ofsset of my Bitmap
. Bitmap
itself is drawn in draw
method):
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();
}
}
Also you can modify View
by using Transformation#getMatrix()
.
UPDATE
In case if you're using Android Animator framework (or compatibility implementation - NineOldAndroids
) you can just declare setter and getter for your custom View
property and animate it directly. Here is an another example:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With