我需要使用
绘制文本canvas.drawText("1",x,y, paint);
但问题是“文本的中心”与我给定的位置不匹配,有什么办法可以做到后者。我已经对该主题进行了很多搜索,但找不到任何答案。请帮忙。
提前谢谢你
最佳答案
您需要在绘画实例上设置对齐方式:
paint.setTextAlign(Paint.Align.CENTER);
在绘图之前。
编辑: 根据您的指示,您也希望它垂直居中,我会采用与此类似的方法:
paint.setColor(Color.WHITE);
paint.setTextAlign(Align.LEFT);
String text = "Hello";
Rect bounds = new Rect();
float x = 100, y = 100;
paint.getTextBounds(text, 0, text.length(), bounds); // Measure the text
canvas.drawLine(0, y, canvas.getWidth(), y, paint); // Included to show vertical alignment
canvas.drawLine(x, 0, x, canvas.getHeight(), paint); // Included to show horizsontal alignment
canvas.drawText(text, x - bounds.width() * 0.5f, y + bounds.height() * 0.5f, paint); // Draw the text
或者,在绘画上使用中心对齐:
paint.setColor(Color.WHITE);
paint.setTextAlign(Align.CENTER);
String text = "Hello";
Rect bounds = new Rect();
float x = 100, y = 100;
paint.getTextBounds(text, 0, text.length(), bounds); // Measure the text
canvas.drawLine(0, y, canvas.getWidth(), y, paint); // Included to show vertical alignment
canvas.drawLine(x, 0, x, canvas.getHeight(), paint); // Included to show horizsontal alignment
canvas.drawText(text, x, y + bounds.height() * 0.5f, paint); // Draw the text
关于java - 将文本中心与给定位置对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151902/