简体   繁体   中英

Align the texts center with the given position

I need to draw a text using

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

But the problem is that the "text's center" doesn't match with the position I have given,Is there any way I can do the latter.I have done quite a lot of search on the topic,culdn't find any answer.Please help.

Thank You in advance

You'll want to set the alignment on your paint instance:

paint.setTextAlign(Paint.Align.CENTER);

prior to drawing.

See: http://developer.android.com/reference/android/graphics/Paint.html#setTextAlign(android.graphics.Paint.Align )

Edit: Per your indication that you'd also like it centered vertically, I'd go with an approach similar to this:

            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

or, using the center align on the paint:

            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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM