pacote com . . _ . _ ui . widget ; importar android.content.Context ; importar android.graphics.Canvas ; importar android.graphics.Paint ; importar android.graphics.Rect ; importar android.graphics.drawable.Drawable ; importar android.text.style.ImageSpan ; import java.lang.ref.WeakReference ; /** * Nome: CenterImageSpan.java * Autor: lilei * Data: 06/05/2018 * Comentário: // TODO exibe imagens no centro de gráficos mistos */ public class CenterImageSpan extends ImageSpan { private WeakReference < Drawable > mDrawableRef ; public CenterImageSpan ( Context context , int resourceId , int verticalAlignment ) { super ( context , resourceId , verticalAlignment ) ; } @Override public int getSize ( Paint paint , CharSequence text , int start , int end , Paint.FontMetricsInt fontMetricsInt ) { Drawable drawable = getDrawable () ; Rect rect = desenhável . getBounds () ; if ( fontMetricsInt != null ) { Paint.FontMetricsInt fmPaint = paint . getFontMetricsInt () ; int fontHeight = fmPaint . descida -fmPaint . _ ascensão ; int drHeight = rect . inferior - rect . superior ; int centroY = fmPaint . subida + fontHeight / 2 ; fontMetricsInt . subida = centroY - drAltura / 2 ; fontMetricsInt . topo = fontMetricsInt . ascensão ; fontMetricsInt . inferior = centroY + drHeight / 2 ; fontMetricsInt . descida = fontMetricsInt . inferior ; } retorno ret . certo ; } @Override public void draw ( Canvas canvas , CharSequence text , int start , int end , float x , int top , int y , int bottom , Paint paint ) { Drawable drawable = getCachedDrawable () ; tela . salvar () ; Paint.FontMetricsInt fmPaint = pintar . getFontMetricsInt () ; int fontHeight = fmPaint . descida - fmPaint . ascensão ; int centroY = y + fmPaint . descida - fontHeight / 2 ; int transY = centerY - ( drawable . getBounds () . bottom - drawable . getBounds () . top ) / 2 ; tela . traduzir ( x , transY ) ; desenhável . desenhar ( tela ) ; tela . restaurar () ; } private Drawable getCachedDrawable () { WeakReference < Drawable > wr = mDrawableRef ; Drawable d = nulo; if ( wr != null ) { d = wr . obter () ; } if ( d == null ) { d = getDrawable () ; mDrawableRef = new WeakReference <> ( d ) ; } return d ; } }
Classe ImageSpan integrada
Uso específico
TextView txt_explain = view.findViewById(R.id.txt_personal_dialog_explain); String explain = txt_explain.getText().toString(); int start = explain.length(); String explain_pink = "变色字体"; int end = explain.length() + explain_pink.length(); SpannableString spannableString = new SpannableString(explain + explain_pink); //设置颜色 spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff427b")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置问号 ImageSpan image = new CenterImageSpan(mContext, R.mipmap.ic_question, DynamicDrawableSpan.ALIGN_BASELINE); spannableString.setSpan(image, end - 1, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); txt_explain.setText(spannableString);