Bitmap.recycle()绘制后调用它

时间:2013-10-09 16:11:14

标签: android bitmap android-canvas out-of-memory

我遇到了问题。我有一个绘图后监听器,我在其中绘制位图的缩放版本。问题源于这样一个事实:每次放大时我都会做一些缩放(放大放大,缩小缩小)。问题是我无法回收位图,因为我在绘制后尝试这样做

canvas.draw(scaledbitmap,0,0,null);
scaledBitmap.recycle()

我得到Canvas canot绘制回收位图异常

有没有人知道在完成后我会如何回收一个位图,这样另一个可以在之后进行缩放,而且我没有得到OutOfMemoryException崩溃。

一些代码向您展示我正在使用它的方式:

private SpenDrawListener mPosteDrawListener = new SpenDrawListener() {

        @Override
        public void onDraw(Canvas canvas, float x, float y, float ratio,
            float frameStartX, float frameStartY, RectF updateRect) {
            if(mLineDrawingBitmap == null)
                mLineDrawingBitmap = loadLineDrawingBitmap(mLineDrawingFileName);

            Bitmap bm = Bitmap.createScaledBitmap(mLineDrawingBitmap, (int)(mLineDrawingBitmap.getWidth() * ratio), (int)(mLineDrawingBitmap.getHeight() * ratio), true);
            /*
            float pointX = (mScreenRect.width() - bm.getWidth()) / 2;
            float pointY = mScreenRect.height() / 2 - bm.getHeight();
            */
            float pointX = frameStartX - (x * ratio);
            float pointY = frameStartY - (y * ratio);

            //canvas.drawBitmap(bm, 0, 0,null);
            canvas.drawBitmap(bm, pointX, pointY, null);

            //bm.recycle();
        }
    };

1 个答案:

答案 0 :(得分:0)

经过几个小时的试验和错误后,我已经找到了如何很好地扩展并且不会使应用程序崩溃的OutOfMemoryException:下面是在运行时绘制和缩放的代码,没有崩溃(只要图像不是太大)解码时)。我将使用自己的PostDrawListener,但我相信它可以在任何地方使用,只需稍加修改

private SpenDrawListener mPosteDrawListener = new SpenDrawListener() {
    @Override
    public void onDraw(Canvas canvas, float x, float y, float ratio,
        float frameStartX, float frameStartY, RectF updateRect) {
        if(mLineDrawingBitmap == null)
                mLineDrawingBitmap = loadLineDrawingBitmap(mLineDrawingFileName);

        float pointX = frameStartX - (x * ratio);
        float pointY = frameStartY - (y * ratio);

        //Create a new Matrix
        Matrix m = new Matrix();
        //Use any scaling ratio you want
        m.postScale(ratio, ratio);
        //Use any translation you want
        m.postTranslate(pointX, pointY);
        //when using below call you will not be creating a new bitmap, just
        //using the original with runtime modifications    
        canvas.drawBitmap(mLineDrawingBitmap, m, null);

    }
};