上一篇博文解決了圖片溢出的問題假勿,現(xiàn)在又發(fā)現(xiàn)當(dāng)圖片小于TextView寬度的時(shí)候是靠左的这吻,并沒有居中顯示肆糕。這個(gè)問題困擾了好久般堆,在網(wǎng)上也搜索不到這種需求的信息。
探索
TextView 顯示Html內(nèi)容的時(shí)候诚啃,圖片加載是在ImageGetter中的淮摔。getDrawable方法中是獲取drawable對象 還沒繪制上去,所以肯定無法在這里調(diào)整位置始赎。那么就得去尋找繪制的方法:BitmapDrawable這個(gè)類了和橙。
這個(gè)類中我們重寫了draw方法仔燕。
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (bitmap != null) {
canvas.drawBitmap(bitmap, 0, 0, getPaint());
}
}
有一個(gè)canvas畫布。有繪制的對象了那么調(diào)整繪制的位置也是讓圖片居中的一種方式魔招。
所以在這里我使用canvas的寬度晰搀,它的寬度是等于TextView 的寬度的,具體方法如下:
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (bitmap != null) {
int i = canvas.getWidth() - bitmap.getWidth();
canvas.drawBitmap(bitmap, i/2, 0, getPaint());
}
}
利用畫布的寬度減去圖的寬度就是剩余的空白部分了办斑,然后在繪制的時(shí)候x軸偏移i/2即可顯示為居中外恕。
注意:在getDrawable中我處理了圖片寬度大于textView的情況,所以在這里bitmap的寬度是永遠(yuǎn)小于或等于canvas的寬度的乡翅,不存在i<0的情況鳞疲。如果有特殊的需求需要注意這一點(diǎn)。
另外附上完整的ImageGetter類:
class DetailImageGetter implements Html.ImageGetter {
private Context context;
private TextView textView;
DetailImageGetter(Context context, TextView textView) {
this.context = context;
this.textView = textView;
}
@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();
Loger.debug("width: " + width);
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(CommonUtil.resizeBitmap(resource, afterWidth, afterHeight));
} else {
drawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
drawable.setBitmap(resource);
}
textView.invalidate();
textView.setText(textView.getText());
}
});
return drawable;
}
private class UrlDrawable extends BitmapDrawable {
private Bitmap bitmap;
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (bitmap != null) {
int i = canvas.getWidth() - bitmap.getWidth();
canvas.drawBitmap(bitmap, i/2, 0, getPaint());
}
}
void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
}
CommonUtil.resizeBitmap(resource, afterWidth, afterHeight));就是壓縮bitmap 的尺寸蠕蚜。
/**
* 使用Matrix將Bitmap壓縮到指定大小
* @param bitmap
* @param w
* @param h
* @return
*/
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);
}