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

标签 java android

我需要使用

绘制文本

canvas.drawText("1",x,y, paint);

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

提前谢谢你

最佳答案

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

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

关于java - 将文本中心与给定位置对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151902/

相关文章:

java - Spring MVC - 实现 aerospike session

java - 用java编辑mp4标签

android - 如何解决错误 :(5) No resource identifier found for attribute 'iconTint' in package 'android' ?

java - Exoplayer Activity 不播放视频,而是显示空屏幕

android - 修改联系方式

java.lang.ClassNotFoundException : org. springframework.http.converter.json.MappingJackson2HttpMessageConverter

java - 如何限制eclipse编译器

java - 正则表达式匹配/分组字符串中的重复字符

android - 将 XML 中可绘制按钮的大小设置为图像大小

java - 自定义alertdialog android api 10