0

我有问题。我有一个绘制后侦听器,在其中绘制位图的缩放版本。问题源于这样一个事实,即我倾向于在每次缩放时进行一些缩放(放大放大,缩小缩小)。问题是我无法回收位图,因为当我在绘制后尝试这样做时

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

我得到 Canvas 无法绘制回收的位图异常

有谁知道我在完成后如何回收位图,以便之后可以缩放另一个位图,并且我不会遇到 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();
        }
    };
4

1 回答 1

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);

    }
};
于 2013-10-09T19:14:27.403 回答