我解释这一点的最佳方式是提供一个完整的自定义视图示例,您可以从中提取所需的部分。下面是一个实现这一点的视图。
public class CharacterView extends View {
private Paint mCharacterPaint;
private Bitmap mCharacterBitmap;
private Transformation mTransformation;
private AlphaAnimation mFadeOut;
public CharacterView(Context context) {
super(context);
init(context);
}
public CharacterView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CharacterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
//This would be your character image instead
mCharacterBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//We need a paint to efficiently modify the alpha
mCharacterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//This is needed to house the current value during the animation
mTransformation = new Transformation();
//Construct an animation that will do all the timing math for you
mFadeOut = new AlphaAnimation(1f, 0f);
mFadeOut.setDuration(500);
//Use a listener to trigger the end action
mFadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
//Trigger your action to change screens here.
}
@Override
public void onAnimationRepeat(Animation animation) { }
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//In this example, touching the view triggers the animation
// your code would run this sequence when the character reaches the
// appropriate coordinates (P.S. I would not advocate putting this code
// inside of onDraw()
mFadeOut.start();
mFadeOut.getTransformation(System.currentTimeMillis(), mTransformation);
invalidate();
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//...existing drawing code...
canvas.drawBitmap(mCharacterBitmap, 0, 0, mCharacterPaint);
if (mFadeOut.hasStarted() && !mFadeOut.hasEnded()) {
mFadeOut.getTransformation(System.currentTimeMillis(), mTransformation);
//Keep drawing until we are done
mCharacterPaint.setAlpha((int)(255 * mTransformation.getAlpha()));
invalidate();
} else {
//Reset the alpha if animation is canceled
mCharacterPaint.setAlpha(255);
}
}
}
动态修改所绘制内容的透明度的最有效方法是使用Paint
绘图将其应用到您的Canvas
. 您将需要在invalidate()
每个帧转换中不断地查看视图以显示动画,直到角色消失。该示例使用一个Animation
对象和一个Transformation
对象来处理所有时序数学,以使动画看起来确实不错。
这里的要点是您通过一些外部触发器启动动画(我不建议检查何时淡出,在onDraw()
更新这些角色位置的地方可能更好。在我的示例中,为简单起见,我当视图被触摸时开始这个。
此触发器启动动画并获取初始转换值,然后invalidate()
触发一个新的onDraw()
. 在动画运行时,onDraw()
由于invalidate()
每次迭代,油漆上的 alpha 会略有下降,因此会重复。
动画完成后,它会AnimationListener
为你调用 ,所以你可以在onAnimationEnd()
.