Canvas: trying to use a recycled bitmap android.graphics.Bitmap in Android

后端 未结 8 1708
忘掉有多难
忘掉有多难 2020-12-13 17:32

I am working on the crop image class, but encounter a recycled bit map problem:

03-02 23:14:10.514: E/AndroidRuntime(16736): FATAL EXCEPTION: Thread-1470
03-         


        
8条回答
  •  伪装坚强ぢ
    2020-12-13 17:59

    This should fix the issue in accordance to the android documentation here : https://developer.android.com/topic/performance/graphics/manage-memory#java Here's the code just incase the link doesn't work .

        private int cacheRefCount = 0;
    private int displayRefCount = 0;
    ...
    // Notify the drawable that the displayed state has changed.
    // Keep a count to determine when the drawable is no longer displayed.
    public void setIsDisplayed(boolean isDisplayed) {
        synchronized (this) {
            if (isDisplayed) {
                displayRefCount++;
                hasBeenDisplayed = true;
            } else {
                displayRefCount--;
            }
        }
        // Check to see if recycle() can be called.
        checkState();
    }
    
    // Notify the drawable that the cache state has changed.
    // Keep a count to determine when the drawable is no longer being cached.
    public void setIsCached(boolean isCached) {
        synchronized (this) {
            if (isCached) {
                cacheRefCount++;
            } else {
                cacheRefCount--;
            }
        }
        // Check to see if recycle() can be called.
        checkState();
    }
    
    private synchronized void checkState() {
        // If the drawable cache and display ref counts = 0, and this drawable
        // has been displayed, then recycle.
        if (cacheRefCount <= 0 && displayRefCount <= 0 && hasBeenDisplayed
                && hasValidBitmap()) {
            getBitmap().recycle();
        }
    }
    
    private synchronized boolean hasValidBitmap() {
        Bitmap bitmap = getBitmap();
        return bitmap != null && !bitmap.isRecycled();
    }
    

提交回复
热议问题