Android(安卓)TextView的图片和文字居中探索
16lz
2021-01-26
效果图:
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); }
遇到问题:
- canvas.translate()偏移整个canvas,导致水平或垂直方向的图片会显示不全(解决:通过setPaddingRelative()设置偏移量,虽然可以实现效果,但是该方法会执行requestLayout())
- TextView的文字不居中(解决:使用setGravity()设置内容水平或垂直居中)
- 设置左右图片和文字居中时,文字不换行(没解决)
总结:
实现图片和文字居中,完全可以使用布局嵌套TextView(方便,没bug)
github:https://github.com/wudengwei/TextStrongView
更多相关文章
- Android获取SD卡上图片和视频缩略图的几个例子
- Android带文字的ImageButton实现
- Android开机界面logo
- android 双击图片放大,再双击缩小效果 【安卓进化九】
- android读取sd卡图片并进行缩放操作
- android图标大小规范
- Android(安卓)FrameLayout布局中的控件设置居中动态设置
- Android(安卓)图片加载笔记
- android tint使用