将文本中心与给定位置对齐

时间:2012-06-22 07:27:48

标签: java android

我需要使用

绘制文字

canvas.drawText(“1”,x,y,paint);

但问题是“文本的中心”与我给出的位置不符,我有什么方法可以做后者。我已经对这个主题进行了很多搜索,但是找不到任何答案。请帮忙。

提前谢谢

1 个答案:

答案 0 :(得分:6)

您需要在绘图实例上设置对齐方式:

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