在安卓开发中 针对节约app使用成本的情况下给列表图片封装加载工具类并做出优化(采样率压缩)代码
时间: 2024-03-12 16:47:33 浏览: 19
对于安卓开发中的图片加载,为了节约app使用成本,可以对图片进行采样率压缩,降低图片的像素,从而减小图片的内存占用。以下是一个封装图片加载的工具类,并对图片进行采样率压缩的代码示例:
```kotlin
object ImageLoader {
/**
* 采样率压缩图片
*
* @param context 上下文
* @param resId 图片资源ID
* @param reqWidth 期望的图片宽度
* @param reqHeight 期望的图片高度
* @return 经过采样率压缩的图片
*/
fun decodeSampledBitmapFromResource(context: Context, resId: Int, reqWidth: Int, reqHeight: Int): Bitmap {
// 首先获取图片的原始大小
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(context.resources, resId, options)
// 计算采样率
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
// 使用采样率压缩图片
options.inJustDecodeBounds = false
return BitmapFactory.decodeResource(context.resources, resId, options)
}
/**
* 计算采样率
*
* @param options 图片原始大小
* @param reqWidth 期望的图片宽度
* @param reqHeight 期望的图片高度
* @return 采样率
*/
private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
val height = options.outHeight
val width = options.outWidth
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat())
val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat())
inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio
}
return inSampleSize
}
/**
* 加载网络图片
*
* @param context 上下文
* @param url 图片URL
* @param imageView 图片控件
*/
fun loadOnlineImage(context: Context, url: String, imageView: ImageView) {
// 使用Glide库加载图片,并进行采样率压缩
Glide.with(context)
.asBitmap()
.load(url)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
imageView.setImageBitmap(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {}
})
}
/**
* 加载本地图片
*
* @param context 上下文
* @param resId 图片资源ID
* @param reqWidth 期望的图片宽度
* @param reqHeight 期望的图片高度
* @param imageView 图片控件
*/
fun loadLocalImage(context: Context, resId: Int, reqWidth: Int, reqHeight: Int, imageView: ImageView) {
// 使用采样率压缩加载本地图片
val bitmap = decodeSampledBitmapFromResource(context, resId, reqWidth, reqHeight)
imageView.setImageBitmap(bitmap)
}
}
```
以上代码中,`decodeSampledBitmapFromResource`函数用于对图片进行采样率压缩,`calculateInSampleSize`函数用于计算采样率,`loadOnlineImage`函数用于加载网络图片并进行采样率压缩,`loadLocalImage`函数用于加载本地图片并进行采样率压缩。