All Downloads are FREE. Search and download functionalities are using the official Maven repository.

androidMain.BitmapPool.kt Maven / Gradle / Ivy

There is a newer version: 0.19.0
Show newest version
package com.juul.krayon.element.view

import android.graphics.Bitmap
import android.graphics.Color
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** Cache of no-longer-used [Bitmap] that might be useful in the future, to avoid allocating on every draw. */
internal class BitmapPool(
    private val config: Bitmap.Config = Bitmap.Config.ARGB_8888,
) {
    /** Pixel count of the most recently requested bitmap. Used to clear old entries from the pool when an [ElementView] grows. */
    private var size: Long = 0
    private val mutex = Mutex()
    private val pool = ArrayDeque()

    suspend fun acquire(width: Int, height: Int): Bitmap = mutex.withLock {
        val newSize = width.toLong() * height
        if (newSize > size) {
            pool.forEach { it.recycle() }
            pool.clear()
        }
        size = newSize
        pool.removeFirstOrNull()
            ?.apply { if (this.width != width || this.height != height) reconfigure(width, height, config) }
            ?: Bitmap.createBitmap(width, height, config)
    }

    suspend fun release(bitmap: Bitmap) = mutex.withLock {
        if (bitmap.width.toLong() * bitmap.height >= size) {
            bitmap.eraseColor(Color.TRANSPARENT)
            pool.addLast(bitmap)
        } else {
            bitmap.recycle()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy