这个例子是一帧一帧的播放20张图片,通过两个按钮控制播放的开始和停止
frame.xml文件
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <ImageView android:id="@+id/p_w_picpathview"
- android:layout_width="200px"
- android:layout_height="200px"
- android:src="@drawable/anim_01"
- android:scaleType="fitCenter"
- android:layout_centerHorizontal="true"
- android:background="#ffffff" />
- <Button android:id="@+id/start"
- android:text="开始动画"
- android:layout_below="@id/p_w_picpathview"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- <Button android:id="@+id/stop"
- android:text="结束动画"
- android:layout_below="@id/start"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- </RelativeLayout>
其中,ImageView中的android:scaleType属性(ImageView.setScaleType(ImageView.ScaleType))说明:
CENTER_CROP / centerCrop 按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长(宽)
CENTER_INSIDE / centerInside 将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片长/宽等于或小于View的长/宽
FIT_CENTER / fitCenter 把图片按比例扩大/缩小到View的宽度,居中显示 FIT_END / fitEnd 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置
FIT_START / fitStart 把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置
FIT_XY / fitXY 把图片不按比例
- public class FrameActivity extends Activity {
- private ImageView p_w_picpathView;
- private Button start;
- private Button stop;
- private AnimationDrawable animationDrawable;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.frame);
- p_w_picpathView = (ImageView)findViewById(R.id.p_w_picpathview);
- start = (Button)findViewById(R.id.start);
- start.setOnClickListener(start_listener);
- stop = (Button)findViewById(R.id.stop);
- stop.setOnClickListener(stop_listener);
- animationDrawable = new AnimationDrawable();
- //添加每一帧动画
- for (int i = 1; i <= 20; i++) {
- int id = getResources().getIdentifier(
- "anim" + (i > 9 ? "_" : "_0") + i, "drawable", "com.will.frame");
- animationDrawable.addFrame(getResources().getDrawable(id), 150);
- }
- //设置手否重复播放,false为重复
- animationDrawable.setOneShot(false);
- p_w_picpathView.setImageDrawable(animationDrawable);
- }
- //开始播放
- Button.OnClickListener start_listener = new Button.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- animationDrawable.start();
- }
- };
- //停止播放
- Button.OnClickListener stop_listener = new Button.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- animationDrawable.stop();
- }
- };
- }