paintText = new Paint();
paintText.setStrokeWidth(1);
paintText.setAntiAlias(true);
paintText.setColor(Color.RED);
mTextSize = 700;
paintText.setTextSize(mTextSize);
count = "|";//count = "——",为了测试文字是否居中的专用字符
paintText.setTextAlign(Paint.Align.CENTER);//这句话表明画的时候,以文本中间为基准坐标(仅限于X坐标,Y坐标不能靠这句话搞定)
int xPos = (canvas.getWidth() / 2);//表明文本的绘制X坐标以该坐标为中心
int yPos = (int) ((canvas.getHeight() / 2) - ((paintText.descent() + paintText.ascent()) / 2)) ;//得到文本绘制的Y坐标
canvas.drawText(count, xPos, yPos, paintText);
paintText.ascent():
Return the distance above (negative) the baseline
(ascent) based on the current typeface and text size.
返回:以当前文字字体和文字尺寸的为基准,在baseline上方的距离
paintText.descent();与上面相反
效果图:
字符“——”
字符“|”
本文介绍了一种在Android中使文本居中显示的方法。通过调整Paint对象的属性及使用特定公式计算文本的位置,实现了文本在Canvas上的精确居中显示。文章提供了具体的代码示例,包括设置画笔样式、颜色、大小等。
444

被折叠的 条评论
为什么被折叠?



