Android应用开发之关于 android P ImageDecoder 的使用讲解
白羽 2018-12-24 来源 :网络 阅读 1618 评论 0

摘要:本文将带你了解Android应用开发关于 android P ImageDecoder 的使用讲解,希望本文对大家学Android有所帮助。

    本文将带你了解Android应用开发关于 android P ImageDecoder 的使用讲解,希望本文对大家学Android有所帮助。



        

 一个的可以将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;

});

  });

  


          

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!


本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved