今天学习了在指定的地方播放帧动画。
关键代码为:
public class FrameView extends ImageView { private AnimationDrawable anim; public FrameView(Context context) { super(context); } public FrameView(Context context, AttributeSet attrs) { super(context, attrs); } public FrameView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setAnim(AnimationDrawable anim){ this.anim = anim; } public void setLocation(int top,int left){ this.setFrame(left,top,left + 200,top + 200); } @Override protected void onDraw(Canvas canvas) { try{ //反射调用AnimationDrawable里的mCurFrame值 Field field = AnimationDrawable.class .getDeclaredField("mCurFrame"); field.setAccessible(true); int curFrame = field.getInt(anim);// 获取anim动画的当前帧 if (curFrame == anim.getNumberOfFrames() - 1)// 如果已经到了最后一帧 { //让该View隐藏 setVisibility(View.INVISIBLE); } }catch (Exception e){e.printStackTrace();} super.onDraw(canvas); } }
public class MainActivity extends AppCompatActivity { private FrameView fView; private AnimationDrawable anim = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout fly = new FrameLayout(this); setContentView(fly); fView = new FrameView(this); fView.setBackgroundResource(R.anim.anim_zhuan); fView.setVisibility(View.INVISIBLE); anim = (AnimationDrawable) fView.getBackground(); fView.setAnim(anim); fly.addView(fView); fly.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //设置按下时才产生动画效果 if(event.getAction() == MotionEvent.ACTION_DOWN){ anim.stop(); float x = event.getX(); float y = event.getY(); fView.setLocation((int) y - 40,(int)x-20); //View显示的位置 fView.setVisibility(View.VISIBLE); anim.start(); //开启动画 } return false; } }); } }