我使用Align.CENTER水平居中了一段文字,但它并没有将文字垂直居中。
paint.setTextAlign(Align.CENTER);
canvas.drawText(text, fx, fy, paint);
如何垂直居中文本?
StaticLayout yourLayout = new StaticLayout(text, mTextPaint,
canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
false);
canvas.translate((canvas.getWidth() / 2) - (yourLayout.getWidth() / 2), (canvas.getHeight() / 2) - ((yourLayout.getHeight() / 2)));
This work for me.
Align.CENTER
是用于水平对齐的。如果您想要垂直居中,您需要找到文本的最大高度,然后通过使用 canvas.translate
垂直平移来在画布上垂直定位。
StaticLayout yourLayout = new StaticLayout(text, mTextPaint,canvas.getWidth(),Alignment.ALIGN_NORMAL, 1.0f, 0.0f,false);
请在您的代码中实现以上逻辑。 - SanthoshKumar SrikanthaMurali