我正在尝试做一个简单的机器人游戏。这是我第一次做一个,我试图加载所有的精灵和场景作为位图。我已经创建了一个单独的加载器类来加载几个位图,稍后我将使其可运行,但是现在的问题是,即使我已经将位图缩小到尽可能低的质量,我仍然得到一个内存不足的错误。我做错了什么?其他游戏是如何实现图形的呢?以下是load函数的代码:
public Map<Elements, Bitmap> load(ArrayList<BitmapData> level) {
Bitmap bitmap;
Map<Elements, Bitmap> loadedBitmaps = new HashMap<>();
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
byte[] compressedData;
for(BitmapData data : level){
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeResource(mContext.getResources(), data.id, options);
options.inSampleSize = Background.calculateInSampleSize(options, data.size.x, data.size.y);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeResource(mContext.getResources(), data.id, options);
//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, compressed);
//compressedData = compressed.toByteArray();
//bitmap = BitmapFactory.decodeByteArray(compressedData, 0, compressedData.length);
//will the above commented block improve performance??
loadedBitmaps.put(data.element, bitmap);
}
return loadedBitmaps;
}下面是位图数据类:
public class BitmapData {
int id;
Elements element;
Point size;
BitmapData(int id, Elements element, Point size){
this.id = id;
this.element = element;
this.size = size;
}
}我很乐意提供更多,如果它是需要的,我正在加载的图像是大约200-250kbs和范围从大约4-8的数量,取决于场景。
另外,分析器显示80MB分配给图形,50mb分配给java,为什么这些值这么高?java分配的内存达到50mb是正常的吗?
PS:我试着寻找其他解决方案,但我找不到任何解决方案,如果可能的话,我想至少自己做一次,以便更好地了解其他库是如何工作的,如毕加索或glide。
发布于 2018-07-08 00:39:13
一个更简单的解决方案是使用Glide库。
https://github.com/bumptech/glide
将此代码添加到gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
}这是更友好的内存,并将为您照顾一切。github上描述了这些命令,但它很简单,如下所示:
Glide.with(context)
.load(imageSource)
.into(myImageView);https://stackoverflow.com/questions/51224710
复制相似问题