Android TextView加载HTMl图文时,图片溢出界面问题解决
2018-01-16 16:58
731 查看
一、问题
在之前一篇博文中介绍了利用TextView加载Html图文,使用的时ImageGetter来加载图片,但是并没有处理图片过大的情况。解决思路是将Bitmap进行尺寸压缩,另外还要注意修改了图片大小会出现图文重叠的问题。二、解决过程
具体思路就是先获取TextView的宽度width,然后计算出width与 resource.getWidth()的比例。float scale = width / resource.getWidth();
利用这个去算出新的图片宽高。
int afterWidth = (int) (resource.getWidth() * scale); int afterHeight = (int) (resource.getHeight() * scale);
这里需要注意数据类型的转换,防止精度损失。
总体的代码如下:
重新的getDrawable方法:
@Override public Drawable getDrawable(String source) { final UrlDrawable drawable = new UrlDrawable(); Glide.with(context) .load(source) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.RESULT) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { float width = textView.getWidth(); if (resource.getWidth() > width) 4000 { float scale = width / resource.getWidth(); int afterWidth = (int) (resource.getWidth() * scale); int afterHeight = (int) (resource.getHeight() * scale); drawable.setBounds(0, 0, afterWidth, afterHeight); drawable.setBitmap(BitmapUtil.resizeBitmap(resource, afterWidth, afterHeight)); } else { drawable.setBounds(0, 0, resource.getWidth(), resource.getHeight()); drawable.setBitmap(resource); } textView.invalidate(); textView.setText(textView.getText()); } }); return drawable; }
另外尺寸压缩的方法:
public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float scaleWidth = ((float) w) / width; float scaleHeight = ((float) h) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); }
这里是使用Matrix将Bitmap压缩到指定大小。
这样图片就会宽度适应textView的宽度。
相关文章推荐
- Android开发技巧——TextView加载HTML的图片及代码显示问题
- android textView设置html,解决图片和文字不对齐的问题
- android 解决ViewPager加载大量图片内存溢出问题
- Android TextView加载HTMl图文之添加点击事件和查看图片
- Android TextView加载带有多张图片的HTML,并且解决图片造成的OOM
- android 解决ViewPager加载大量图片内存溢出问题
- Android TextView加载HTMl图文之让图片居中显示
- Android开发技巧——TextView加载HTML的图片及代码显示问题
- 有效解决Android加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题(转载)
- android有效解决加载大图片内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android开发——解决加载大图片时内存溢出的问题
- 转载:Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题
- Android有效解决加载大图片时内存溢出的问题