val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, R.drawable.a, options)
val outWidth = options.outWidth
val outHeight = options.outHeight
val width = mainBinding.ivLoadImg.width
val height = mainBinding.ivLoadImg.height
Log.e("==","with=$width///height="+height)
Log.e("==","outwidth=$outWidth+///+outheight=$outHeight")
var inSmalpSize=1
if (outWidth>width||outHeight>height){
val round1 = Math.round(outWidth * 1.0f / width)
val round2 = Math.round(outHeight * 1.0f / height)
inSmalpSize = Math.max(round1, round2)
}
options.inJustDecodeBounds=false
options.inSampleSize=inSmalpSize
Log.e("===","$inSmalpSize")
val bitm = BitmapFactory.decodeResource(resources, R.drawable.a, options)
mainBinding.ivLoadImg.setImageBitmap(bitm)
}
關于Option 參數介紹
inJustDecodeBounds:
如果將這個值置為true,那么在解碼的時候將不會返回bitmap,只會返回這個bitmap的尺寸。這個屬性的目的是,如果你只想知道一個bitmap的尺寸,但又不想將其加載到內存時。這是一個非常有用的屬性。
inSampleSize:
這個值是一個int,當它小于1的時候,將會被當做1處理,如果大于1,那么就會按照比例(1 / inSampleSize)縮小bitmap的寬和高、降低分辨率,大于1時這個值將會被處置為2的倍數。例如,width=100,height=100,inSampleSize=2,那么就會將bitmap處理為,width=50,height=50,寬高降為1 / 2,像素數降為1 / 4。
inPreferredConfig:
這個值是設置色彩模式,默認值是ARGB_8888,在這個模式下,一個像素點占用4bytes空間,一般對透明度不做要求的話,一般采用RGB_565模式,這個模式下一個像素點占用2bytes。
inPremultiplied:
這個值和透明度通道有關,默認值是true,如果設置為true,則返回的bitmap的顏色通道上會預先附加上透明度通道。
inDither:
這個值和抖動解碼有關,默認值為false,表示不采用抖動解碼。如果想知道什么是抖動解碼,請參看我另一篇文章:http://blog.csdn.net/haozipi/article/details/47185535
inDensity:
表示這個bitmap的像素密度(對應的是DisplayMetrics中的densityDpi,不是density)。
inTargetDensity:
表示要被畫出來時的目標像素密度(對應的是DisplayMetrics中的densityDpi,不是density)。
inScreenDensity:
表示實際設備的像素密度(對應的是DisplayMetrics中的densityDpi,不是density)。
inScaled:
設置這個Bitmap是否可以被縮放,默認值是true,表示可以被縮放。
ps:inDensity,inTargetDensity,inScreenDensity三個值的具體關系請參看我的另一篇文章:http://blog.csdn.net/haozipi/article/details/47185917
inPurgeable和inInputShareable:
這兩個值一般是一起使用,設置為true時,前者表示空間不夠是否可以被釋放,后者表示是否可以共享引用。這兩個值在Android5.0后被棄用。
inPreferQualityOverSpeed:
這個值表示是否在解碼時圖片有更高的品質,僅用于JPEG格式。如果設置為true,則圖片會有更高的品質,但是會解碼速度會很慢。
outWidth和outHeight:
表示這個Bitmap的寬和高,一般和inJustDecodeBounds一起使用來獲得Bitmap的寬高,但是不加載到內存。