您的位置:首页 > 移动开发 > Android开发

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的宽度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: