一、問題
在之前一篇博文中介紹了利用TextView加載Html圖文躁垛,使用的時ImageGetter來加載圖片剖毯,但是并沒有處理圖片過大的情況。解決思路是將Bitmap進(jìn)行尺寸壓縮教馆,另外還要注意修改了圖片大小會出現(xiàn)圖文重疊的問題逊谋。
二、解決過程
具體思路就是先獲取TextView的寬度width土铺,然后計算出width與 resource.getWidth()的比例胶滋。
float scale = width / resource.getWidth();
利用這個去算出新的圖片寬高。
int afterWidth = (int) (resource.getWidth() * scale);
int afterHeight = (int) (resource.getHeight() * scale);
這里需要注意數(shù)據(jù)類型的轉(zhuǎn)換舒憾,防止精度損失镀钓。
總體的代碼如下:
重新的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) {
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);
}
// 這兩行代碼是讓文本刷新一下 不會出現(xiàn)圖文重疊
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壓縮到指定大小。
這樣圖片就會寬度適應(yīng)textView的寬度镀迂。