效果图:

 TextView图片文字居中实现思路:获取TextView中图片和文字的宽度和高度,并根据TextView的宽高计算居中所需要的偏移量。

实现核心代码:

    @Override    protected void onDraw(Canvas canvas) {        if (isTextDrawableCenter) {            if (drawableTop != null || drawableBottom != null) {                int textHeight,drawableHeight;                //文本行数*行高度(行高度包含getLineSpacingExtra())                if (getMaxLines() < getLineCount()) {                    textHeight = getMaxLines()*getLineHeight();                } else {                    textHeight = getLineCount()*getLineHeight();                }                drawableHeight = drawableTopHeight + drawableBottomHeight;                float bodyHeight = textHeight + drawableHeight + getCompoundDrawablePadding();                int dy = (int) ((getHeight() - bodyHeight) * 0.5f);                //setPaddingRelative(0, dy,0,dy);                if (!isSetPadding) {                    setPaddingRelative(0, dy,0,dy);                    isSetPadding = true;                }//                canvas.translate(0, dy);            }            if (drawableLeft != null || drawableRight != null) {                float textWidth;                int drawableWidth;                Rect rect = new Rect();                //计算文本宽度                textWidth = getPaint().measureText(getText().toString());                drawableWidth = drawableLeftWidth + drawableRightWidth;                float bodyWidth = textWidth + drawableWidth + getCompoundDrawablePadding();                int dx = (int) ((getWidth() - bodyWidth) * 0.5f);                //setPaddingRelative(dx, 0,dx,0);                if (!isSetPadding) {                    setPaddingRelative(dx, 0,dx,0);                    isSetPadding = true;                }            }        }        super.onDraw(canvas);    }

 遇到问题:

  1. canvas.translate()偏移整个canvas,导致水平或垂直方向的图片会显示不全(解决:通过setPaddingRelative()设置偏移量,虽然可以实现效果,但是该方法会执行requestLayout())
  2. TextView的文字不居中(解决:使用setGravity()设置内容水平或垂直居中)
  3. 设置左右图片和文字居中时,文字不换行(没解决)

总结:

 实现图片和文字居中,完全可以使用布局嵌套TextView(方便,没bug)

github:https://github.com/wudengwei/TextStrongView

更多相关文章

  1. Android获取SD卡上图片和视频缩略图的几个例子
  2. Android带文字的ImageButton实现
  3. Android开机界面logo
  4. android 双击图片放大,再双击缩小效果 【安卓进化九】
  5. android读取sd卡图片并进行缩放操作
  6. android图标大小规范
  7. Android(安卓)FrameLayout布局中的控件设置居中动态设置
  8. Android(安卓)图片加载笔记
  9. android tint使用

随机推荐

  1. 陈丹琦博士论文翻译:神经阅读理解与超越(Ne
  2. 落地三年,两次架构升级,网易的Service Mesh
  3. 机器学习对计量经济学的影响, AEA年会独
  4. 内生变量的交互项如何寻工具变量, 交互项
  5. 无代码开发,站到了程序员鄙视链顶端
  6. 3-31(string底层实现)
  7. Prometheus 之 K8S系统组件服务监控
  8. 2019.1.1, see you again
  9. 听说你还没读过 Bert 源码?
  10. 易错:函数方式实现二分查找整形数组