android - 如何处理android中位图的OOM异常

标签 android android-canvas textview android-bitmap

我正在使用摄影应用程序从 TextView 创建位图。当我尝试从大文本应用程序创建位图时崩溃。和 LogCat 显示 Out Of Memory 异常

创建位图的方法

protected Bitmap getBitmapFromView(View v) {
        int w, h;
        Bitmap b = null;
        KeyboardActivity.setTextInTextView((TextView) v, this,
                this.tvClass.text);
        ((TextView) v).setMinLines(1);
        if (this.tvClass.isStrick) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 16);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -17);
        }
        if (this.tvClass.isUnderline) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 8);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -9);
        }
        if (this.tvClass.isBold) {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | 32);
        } else {
            ((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() & -33);
        }
        ((TextView) v)
                .setGravity(this.tvClass.gravity1 | this.tvClass.gravity2);
        try {
            if (VERSION.SDK_INT <= 25) {
                v.measure(0, 0);
                w = v.getMeasuredWidth() + 10;
                h = v.getMeasuredHeight();
                v.layout(0, 0, w, h);
            } else {
                w = v.getWidth();
                h = v.getHeight();
            }
            if (w == 0) {
                w = 110;
            }
            if (h == 0) {
                h = 70;
            }
        } catch (Exception e) {
            w = 110;
            h = 7;
        }

        try {
            // this line generate OOM Exception 
            b = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        } catch (Exception e) {
           // Exception is not handle
        }

        Canvas c = new Canvas(b);
        v.draw(c);
        c.drawColor((((255 - this.tvClass.alpha) * 2) & 1) << 24, Mode.DST_OUT);
        c.save();
        c.rotate(90.0f, 0.0f, 0.0f);
        v.setVisibility(8);
        c.restore();
        return b;
    }

最佳答案

更改为

 catch(OutOfMemoryError oom){
        // out of memory does not extends from Exception
  }

http://developer.android.com/reference/java/lang/OutOfMemoryError.html

这应该行得通

关于android - 如何处理android中位图的OOM异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513842/

相关文章:

java - 从像素坐标在图片上绘制矩形

android - 查找 Android 应用程序的包名称以使用 Intent 从 Web 启动 Market 应用程序

javascript - Android 拖动事件不适用于带有 ionic 的 4.4.2

android - 使用自定义 BaseAdapter 检查 GridView 中的复选框

android - SurfaceView 实现 Runnable - 线程不启动

android - 如何以编程方式将RGB代码转换为十六进制并设置为Android中 TextView 或按钮的背景颜色

android - 获取最后一个位置,有很多方法

android - 如何在 Android 中使用 Canvas 设计图表?

android - 表格行内的 TextView 中的优先级

android - 尽管是 "clickable",但单击时 TextView 不提供反馈