我试图使用AsyncTask加载位图,以便将其加载到UI Thread之外,因为它太慢了。 不幸的是,启动应用程序时出现问题。
AsyncTask是在“ BitmapBank”类内部声明的类,用于处理应用程序的不同位图。我这样做是为了避免您无法从Asynctask返回某些信息的事实。
这是我的代码:
public Bitmap loadBitmap(Drawable drawable){
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);
return bitmap;
}
private Bitmap scaleImage(Bitmap bitmap, int ratio){
float widthHeightRatio = (float)(bitmap.getHeight())/(float)(bitmap.getWidth());
int scaleHeight = (int)(widthHeightRatio * AppConstants.SCREEN_WIDTH/ratio);
return Bitmap.createScaledBitmap(bitmap, AppConstants.SCREEN_WIDTH/ratio, scaleHeight, false);
}
private class BitmapTask extends AsyncTask<Drawable, Void, Void> {
public BitmapTask(){
super();
}
@Override
protected Void doInBackground(Drawable... drawables) {
rocket = prepareBitmap(drawables[0]);
astronaut = prepareBitmap(drawables[1]);
bloc = prepareBitmap(drawables[2]);
background = prepareBitmap(drawables[3]);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
rocket = scaleImage(rocket, 10);
astronaut = scaleImage(astronaut, 20);
bloc = scaleImage(bloc, AppConstants.NB_BLOCS);
background = scaleImage(background, 1);
}
}
这是logcat:
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 121701132 byte allocation with 16777216 free bytes and 86MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:975)
at android.graphics.Bitmap.createBitmap(Bitmap.java:946)
at android.graphics.Bitmap.createBitmap(Bitmap.java:913)
at com.example.myapplication.BitmapBank.prepareBitmap(BitmapBank.java:93)
at com.example.myapplication.BitmapBank$BitmapTask.doInBackground(BitmapBank.java:117)
at com.example.myapplication.BitmapBank$BitmapTask.doInBackground(BitmapBank.java:106)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
感谢您的光临!
答案 0 :(得分:0)
我建议您使用自动解决问题的“ Glide”库。 Glide是一个开放源代码的Android库,用于加载动画图像,视频和GIF。使用Glide,您可以上传和显示来自许多不同来源的媒体,例如远程服务器或本地文件系统。
Glide.with(context)
.load(new File(fileUri.getPath())) // Uri of the picture
.into(profileAvatar);