goyourfly / DailyBread

No description, website, or topics provided.
3 stars 0 forks source link

BitmapFactory.Options.inBitmap #3

Open goyourfly opened 5 years ago

goyourfly commented 5 years ago
goyourfly commented 5 years ago

补充一下:是否可以复用 Bitmap 判断条件

private fun getBytesPerPixel(config: Bitmap.Config?): Int {
    var config = config
    if (config == null) {
        config = Bitmap.Config.ARGB_8888
    }

    val bytesPerPixel: Int
    when (config) {
        Bitmap.Config.ALPHA_8 -> bytesPerPixel = 1
        Bitmap.Config.RGB_565, Bitmap.Config.ARGB_4444 -> bytesPerPixel = 2
        Bitmap.Config.ARGB_8888 -> bytesPerPixel = 4
        else -> bytesPerPixel = 4
    }
    return bytesPerPixel
}

fun canUseForInBitmap(
        candidate: Bitmap, targetOptions: BitmapFactory.Options): Boolean {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // From Android 4.4 (KitKat) onward we can re-use if the byte size of
        // the new bitmap is smaller than the reusable bitmap candidate
        // allocation byte count.
        val width = targetOptions.outWidth / targetOptions.inSampleSize
        val height = targetOptions.outHeight / targetOptions.inSampleSize
        val byteCount = width * height * getBytesPerPixel(candidate.config)

        try {
            return byteCount <= candidate.allocationByteCount
        } catch (e: NullPointerException) {
            return byteCount <= candidate.height * candidate.rowBytes
        }

    }
    // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
    return (candidate.width == targetOptions.outWidth
            && candidate.height == targetOptions.outHeight
            && targetOptions.inSampleSize == 1)
}