天天看点

Android TextView的图片和文字居中探索

效果图:

Android TextView的图片和文字居中探索

 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