我需要使用
canvas.drawText("1",x,y, 油漆);
但问题是“文本的中心”与我给出的位置不匹配,有什么办法可以做到后者。我对该主题进行了很多搜索,但没有找到任何答案。请帮忙。
先感谢您
您需要在您的绘画实例上设置对齐方式:
paint.setTextAlign(Paint.Align.CENTER);
在绘图之前。
请参阅:http: //developer.android.com/reference/android/graphics/Paint.html#setTextAlign (android.graphics.Paint.Align )
编辑: 根据您的指示,您还希望它垂直居中,我将采用类似于此的方法:
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