ImageSpan图片不能居中的问题

itlao6 原创 开发&源码评论595字数 1352阅读4分30秒阅读模式

使用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参数,文章源自IT老刘-https://itlao6.com/523.html

分别有文章源自IT老刘-https://itlao6.com/523.html

Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、文章源自IT老刘-https://itlao6.com/523.html

Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、文章源自IT老刘-https://itlao6.com/523.html

Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、文章源自IT老刘-https://itlao6.com/523.html

Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)文章源自IT老刘-https://itlao6.com/523.html

四个选项,包括即与span指定的内容格式一致,如span为红色字体,如果前面包括后面不包括,则在span内容的前面输入是红色字体(与span一致),后面输入是默认颜色字体。如果ImageSpan是图片,则需要设置前后都不包括,不然,包括的部分输入文字会不可见。文章源自IT老刘-https://itlao6.com/523.html

ps: 之前在其他博客写的文章(2016-05-18 09:58)
源码下载
http://itlao5.com/wp/file/MyImageSpan.java文章源自IT老刘-https://itlao6.com/523.html

文章源自IT老刘-https://itlao6.com/523.html文章源自IT老刘-https://itlao6.com/523.html
继续阅读
weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
itlao6
  • 本文由 发表于 2018年 7月 26日 14:36:59
  • 转载请务必保留本文链接:https://itlao6.com/523.html
评论  0  访客  0
匿名

发表评论

匿名网友

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

确定