首页 > 解决方案 > java.lang.OutOfMemoryError:无法分配 7144212 字节分配,其中 4194304 字节和 4MB 直到 OOM

问题描述

我正在尝试通过画布将字符串文本转换为位图,从字符串数组生成图像,并且我在单个活动中生成 50 个图像。

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    Bitmap copy;
    DisplayMetrics displayMetrics = new DisplayMetrics ();
    getWindowManager ().getDefaultDisplay ().getMetrics (displayMetrics);
    int width = displayMetrics.widthPixels;

    String text = listArray[position];
    text.replace("\'", "");
    text.replace("\"", "");

    Bitmap icon = BitmapFactory.decodeResource (mContext.getResources (), R.drawable.abraham);
    TextPaint paint = new TextPaint ();
    paint.setColor (Color.parseColor ("#000000"));
    paint.setTextSize ((width / 10) - (text.length () / 6));
    paint.setTypeface (Typeface.create (Typeface.createFromAsset (mContext.getAssets (), "fonts/underwood_champion.ttf"), Typeface.BOLD));
    copy = icon.copy (Bitmap.Config.RGB_565, true);
    Canvas canvas = new Canvas (copy);
    StaticLayout layout = new StaticLayout (text, paint, canvas.getWidth () - 100, Layout.Alignment.ALIGN_CENTER, 1.3f, 3, false);
    canvas.translate (100, (width / 2)+30);//(canvas.getHeight()/2)-(text.length ())); //position the text
    layout.draw (canvas);

    int size = width / 2;
    imageView = new ImageView (mContext);
    imageView.setLayoutParams (new GridView.LayoutParams (size, size));
    imageView.setScaleType (ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding (30, 30, 30, 30);
    imageView.setImageBitmap (copy);
    return imageView;
}

注意:我已经做了这一步。

<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

这是日志猫

    PID: 7957 java.lang.OutOfMemoryError: Failed to allocate a 7144212 byte allocation with 4194304 free bytes and 4MB until OOM at 
dalvik.system.VMRuntime.newNonMovableArray(Native Method) at
android.graphics.Bitmap.nativeCopy(Native Method) at 
android.graphics.Bitmap.copy(Bitmap.java:592) at 
com.ahsaashafeez.textoverbitmap.MainActivity$ImageAdapter.getView(MainActivity.java:84) at
android.widget.AbsListView.obtainView(AbsListView.java:2362) at 
android.widget.GridView.makeAndAddView(GridView.java:1439) 

标签: androidexceptionbitmapout-of-memoryandroid-largeheap

解决方案


推荐阅读