Android P ImageDecoder 封装工具类
翻阅安卓版本信息时,发现在Android P中新增了一个用于替代BitmapFactory
的类ImageDecoder
类,稍微研究了一下,感觉很有趣,便尝试着写了个工具类出来丰富我的个人开发框架
基本用法
// 测试方法 java
void test(File file){
ImageDecoder.Source source = ImageDecoder.createSource(file);
Drawable d = ImageDecoder.decodeDrawable(source);
Bitmap b = ImageDecoder.decodeBitmap(source);
}
// 测试方法 kotlin
fun test(file: File){
val source = ImageDecoder.createSource(file)
val drawable = ImageDecoder.decodeDrawable(source)
val bitmap = ImageDecoder.decodeBitmap(source)
}
上面的代码就是通过ImageDecoder
加载一个本地图片文件的过程。很简单,过程基本就是先获取一个ImageDecoder.Source
实例,再将该实例作为参数获取图片。该方法是耗时操作,不建议在主线程中使用。
加载监听
一般为了我们会为了一些原因在图片加载出来前进行一些操作,比如防止OOM而提前进行压缩,或者将图片进行一些处理。比如下面的官方例子就是在图片加载前对图片进行圆角化处理
//官方用到了java 1.8 的lambda表达式
void test(){
Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
decoder.setPostProcessor((canvas) -> {
// This will create rounded corners.
Path path = new Path();
path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
int width = canvas.getWidth();
int height = canvas.getHeight();
path.addRoundRect(0, 0, width, height, 20, 20, Path.Direction.CW);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.TRANSPARENT);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
canvas.drawPath(path, paint);
return PixelFormat.TRANSLUCENT;
});
});
}