本文参考自官方文档,链接如下:
一个的可以将PNG, JPEG, WEBP, GIF, or HEIF 格式的图片的转换成Drawable 或者Bitmap 对象的类。
要使用它, 首先使用createSource 创建一个source, 例如解码一个文件使用createSource(File) ,将返回值传入decodeDrawable(Source) 或者 decodeBitmap(Source):
File file = new File(...);
ImageDecoder.Source source = ImageDecoder.createSource(file);
Drawable drawable = ImageDecoder.decodeDrawable(source);
source是可以复用的方需要,将图片解码成不同的形态,例如修改宽高。
第二方法还可以传递OnHeaderDecodedListener,这里ImageInfo存放的是原始的图片的宽和高。可以修改用来修改图片宽高的时候修改SampleSize。
OnHeaderDecodedListener listener = new OnHeaderDecodedListener() {
public void onHeaderDecoded(ImageDecoder decoder, ImageInfo info, Source source) {
decoder.setTargetSampleSize(2);
}
};
Drawable drawable = ImageDecoder.decodeDrawable(source, listener);
如果要解码的图片是gif,会被解码成AnimatedImageDrawable 使用方法如下:
Drawable drawable = ImageDecoder.decodeDrawable(source);
if (drawable instanceof AnimatedImageDrawable) {
((AnimatedImageDrawable) drawable).start();
}
默认解码出来的bitmap是不可变,但是仍然可以使用PostProcessor来添加一些自定义的效果,例如:
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;
});
});
如果解码的照片是不完整的或者包含错误,解码的时候会抛出DecodeException,一些情况下,可能已经解码出一部分的照片,这个时候传递OnPartialImageListener ,并返回true,就只显示解码出来的部分,剩余部分使用空白代替。
Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
decoder.setOnPartialImageListener((DecodeException e) -> {
// Returning true indicates to create a Drawable or Bitmap even
// if the whole image could not be decoded. Any remaining lines
// will be blank.
return true;
});
});
有错误的地方,欢迎指正,谢谢。