这里面有几个要点和环节需要注意:
1,AssetManager读取事先放置到assets目录下的原始图片资源文件,组装成Android的Bitmap数组。
文件结构如图:
2,把1中读取到的Bitmap数组每隔一个较小时间内(如25ms)不间断循环设置到ImageView里面,从而在视觉上形成一种动画效果。
代码:
package zhangphil.test;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
public class AnimationActivity extends AppCompatActivity {
private boolean mStartLoadingAnimation = false;
private ImageView mImageView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animation_activity);
mImageView = findViewById(R.id.image);
mStartLoadingAnimation = true;
loadingAnimation();
}
private void loadingAnimation() {
new Thread(new Runnable() {
@Override
public void run() {
Bitmap[] bitmaps = getBimaps();
if (bitmaps == null || bitmaps.length == 0) {
return;
}
int i = 0;
while (mStartLoadingAnimation) {
mImageView.setImageBitmap(bitmaps[i++ % bitmaps.length]);
try {
TimeUnit.MILLISECONDS.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
private Bitmap[] getBimaps() {
final String parentPath = "loading";
Bitmap[] bitmaps = null;
AssetManager am = getAssets();
try {
String[] files = am.list(parentPath);
bitmaps = new Bitmap[files.length];
for (int i = 0; i < files.length; i++) {
InputStream is = am.open(parentPath + "/" + files[i]);
bitmaps[i] = BitmapFactory.decodeStream(is);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmaps;
}
}
原文发布时间为:2018-08-19
本文来自云栖社区合作伙伴“Android开发中文站”,了解相关信息可以关注“Android开发中文站”。