Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将文本中心与给定位置对齐_Java_Android - Fatal编程技术网

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

Java 将文本中心与给定位置对齐,java,android,Java,Android,我需要画一个文本使用 画布.绘图文本(“1”,x,y,绘画) 但问题是“文本中心”与我给出的位置不匹配,有没有办法做到后一点。我在这个主题上做了很多搜索,但没有找到任何答案。请帮助 提前感谢您您需要在paint实例上设置对齐方式: paint.setTextAlign(Paint.Align.CENTER); 在绘图之前 见:) 编辑: 根据您的指示,您也希望它垂直居中,我将采用类似的方法: paint.setColor(Color.WHITE);

我需要画一个文本使用

画布.绘图文本(“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

抱歉,这没有帮助…我希望文本的中心与我给出的位置对齐。。(例如…如果我给出“1”,那么1s垂直线的中心应该与我给出的位置重合…我编辑了我的答案,以显示通过测量文本然后应用偏移来水平和垂直对齐的方法。我已将其更改为左对齐,但您仍然可以使用“对齐中心”并直接使用x值,但它对s起作用谢谢,非常有帮助。