Android ImageDecoder把瘦高/扁平大图相当于fitCenter模式decode成目标小尺寸Bitmap,Kotlin
Kotlin
val sz = Size(MainActivity.SIZE, MainActivity.SIZE)
val src = ImageDecoder.createSource(mContext?.contentResolver!!, uri)
val bitmap = ImageDecoder.decodeBitmap(src, object : ImageDecoder.OnHeaderDecodedListener {
override fun onHeaderDecoded(decoder: ImageDecoder, info: ImageDecoder.ImageInfo, source: ImageDecoder.Source) {
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
//最小边。
val minEdge = Math.min(info.size.width, info.size.height)
//竖长或扁平的图,按照原图最小的边,把原图缩小到目标宽高的采样值。
val sample = if (minEdge == info.size.width) {
info.size.width / sz.width
} else {
info.size.height / sz.height
}
//如果原始图/视频尺寸比目标的尺寸大。
if (sample > 1) {
val cx = (info.size.width) / 2
val cy = (info.size.height) / 2
val rect = Rect(cx - minEdge / 2, cy - minEdge / 2, cx + minEdge / 2, cy + minEdge / 2)
decoder.crop = rect
}
}
})