ImageSpan图片不能居中的问题

  • 3,541 views
  • 阅读模式

使用ImageSpan的童鞋应该都会遇到这样一个困惑,图片不能居中显示,ImageSpan中只有ImageSpan.ALIGN_BASELINE与ImageSpan.ALIGN_BOTTOM两个选项,关键是即使设置了这个参数,在不同手机上可能出现的情况还不同,同一段代码,可能有的居上,有的居下...
其实这个很容易解决,继承ImageSpan重写getSize()和draw()方法即可

@Override  
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {  
  try {
    Drawable d = getDrawable();  
    canvas.save();  
    int transY = 0;  
    transY = ((bottom-top) - d.getBounds().bottom) / 2+top;  
    canvas.translate(x, transY);  
    d.draw(canvas);  
    canvas.restore();
   } catch (Exception e) {
   }  
 }  
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
  try {
    Drawable d = getDrawable();
    Rect rect = d.getBounds();
    if (fm != null) {
      FontMetricsInt fmPaint = paint.getFontMetricsInt();
      int fontHeight = fmPaint.bottom - fmPaint.top;
      int drHeight = rect.bottom - rect.top;

      int top = drHeight / 2 - fontHeight / 4;
      int bottom = drHeight / 2 + fontHeight / 4;

      fm.ascent = -bottom;
      fm.top = -bottom;
      fm.bottom = top;
      fm.descent = top;
    }
    return rect.right;
  } catch (Exception e) {
    return 20;
  }
}

另外在设置spannString.setSpan最后一个flags参数,

分别有

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、

Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、

Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、

Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)

四个选项,包括即与span指定的内容格式一致,如span为红色字体,如果前面包括后面不包括,则在span内容的前面输入是红色字体(与span一致),后面输入是默认颜色字体。如果ImageSpan是图片,则需要设置前后都不包括,不然,包括的部分输入文字会不可见。

ps: 之前在其他博客写的文章(2016-05-18 09:58)
源码下载
http://itlao5.com/file/MyImageSpan.java

weinxin
扫码关注微信公众号--IT老五
微信扫一扫关注公众号,获取更多实用app,订阅地址不定时更新
Liu, Thinkin
  • 本文由 发表于 2018-07-26 14:36:59
  • 转载请务必保留本文链接:https://itlao5.com/523.html
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定