ImageSpan 居中顯示

要實現Textview中的圖文混排需要讓圖片基於文字居中顯示這個就需要自定義ImageSpan 並重寫其ondraw的方法來實現,

先看效果那個紅點和文字 就居中顯示了

OK直接上代碼

package com.vc.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.style.ImageSpan;

import java.lang.ref.WeakReference;

/**
 * imagespan 居中顯示
 */
public class ImageSpanCentre extends ImageSpan {


    public  static final int CENTRE = 2;

    public ImageSpanCentre(@NonNull Drawable d, int verticalAlignment) {
        super(d, verticalAlignment);

    }

    public ImageSpanCentre(@NonNull Context context, @NonNull Bitmap b, int verticalAlignment) {
        super(context, b, verticalAlignment);
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        Drawable b = getCachedDrawable();
        canvas.save();


        int transY = 0;
        if (mVerticalAlignment == ALIGN_BASELINE) {
            transY -= paint.getFontMetricsInt().descent;
        }else if(mVerticalAlignment==ALIGN_BOTTOM){
            transY=  bottom - b.getBounds().bottom;
        }else {
            Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();

             // y 是基準線  Ascent是基準線 之上字符最高處的距離   descent 是基準線之下字符最低處的距離
            transY= (y + fontMetricsInt.descent + y + fontMetricsInt.ascent) / 2 - b.getBounds().bottom/2;

        }

        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }


    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<Drawable>(d);
        }

        return d;
    }

    private WeakReference<Drawable> mDrawableRef;


}

至此自定義的imageSpan 就OK了,只截傳入ImageSpanCentre.CENTRE 就OK了,


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章