关于Bitmap中的inBitmap变量的学习与使用
2019獨角獸企業重金招聘Python工程師標準>>>
inBitmap是在BitmapFactory中的內部類Options的一個變量,簡單而言,使用該變量可以復用舊的Bitmap的內存而不用重新分配以及銷毀舊Bitmap,進而改善運行效率。
關于Bitmap的相關知識可以查看我寫的Android中Bitmap的深入探討總結。
inBitmap知識點
inBitmap變量是在Android 3.0+版本加入到系統源碼當中,也就意味著inBitmap參數只有在Android 3.0+版本及以上能夠正常使用,當你的app版本低于3.0的時候,還是老老實實的使用bitmap.recycle()進行Bitmap的回收操作;在Android 3.0+以上根據系統版本的不同,使用inBitmap的規則也不相同,具體區分如下:
- 4.4之前的版本inBitmap只能夠重用相同大小的Bitmap內存區域。簡單而言,被重用的Bitmap需要與新的Bitmap規格完全一致,否則不能重用。
- 4.4之后的版本系統不再限制舊Bitmap與新Bitmap的大小,只要保證舊Bitmap的大小是大于等于新Bitmap大小即可。
除上述規則之外,舊Bitmap必須是mutable的,這點也很好理解,如果一個Bitmap不支持修改,那么其內存自然也重用不了。Ok,關于inBitmap的知識點理論上也就那么多。Google為了幫助我們更好的管理Bitmap,也出了一個視頻,視頻地址如下:
https://www.youtube.com/watch?v=_ioFW3cyRV0&index=17&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE
并且附帶上了一個使用inBitmap的Demo:
https://developer.android.com/topic/performance/graphics/manage-memory.html#java
下面貼視頻中兩張圖更好的幫助一下理解:
使用inBitmap之前:
使用inBitmap之后:
inBitmap的疑問
針對上述的理解,這里有一個疑問需要去確認一下:
- inBitmap的解碼模式跟新Bitmap的不同是否能夠重用成功
解決這個疑問可以查看Google官方的inBitmap Demo來回答問題:
/*** candidate:舊的圖片,targetOptions:新的圖片的Options*/ private fun canUseForInBitmap(candidate: Bitmap, targetOptions: BitmapFactory.Options): Boolean {return 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: Int = targetOptions.outWidth / targetOptions.inSampleSizeval height: Int = targetOptions.outHeight / targetOptions.inSampleSizeval byteCount: Int = width * height * getBytesPerPixel(candidate.config)byteCount <= candidate.allocationByteCount} else {// On earlier versions, the dimensions must match exactly and the inSampleSize must be 1candidate.width == targetOptions.outWidth&& candidate.height == targetOptions.outHeight&& targetOptions.inSampleSize == 1} }/*** A helper function to return the byte usage per pixel of a bitmap based on its configuration.*/ private fun getBytesPerPixel(config: Bitmap.Config): Int {return when (config) {Bitmap.Config.ARGB_8888 -> 4Bitmap.Config.RGB_565, Bitmap.Config.ARGB_4444 -> 2Bitmap.Config.ALPHA_8 -> 1else -> 1} }這里可以看出,只要新的Bitmap的內存小于舊Bitmap的內存大小,即可進行復用的操作,那么跟解碼模式沒有必然的聯系。
inBitmap的使用
關于inBitmap的使用,可以根據谷歌的官方例子進行設計和開發,不過維護起來需要一定的工作量。當然在市面上成熟的圖片框架中,如Glide內部也使用了inBitmap作為緩存復用的一種方式。總而言之,根據項目以及業務來選擇實現方式即可,不必過分糾結。
轉載于:https://my.oschina.net/u/3863980/blog/3019921
總結
以上是生活随笔為你收集整理的关于Bitmap中的inBitmap变量的学习与使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: window环境变量
- 下一篇: 【初级算法:树】