Text Alignment and Boundaries

Now, you might wonder how the coordinates of the preceding method relate to the rectangle the text string fills. Do they specify the top-left corner of the rectangle the text is contained in? The answer is a bit more complicated. The Paint instance has an attribute called the align setting. It can be set via this method of the Paint class:

Paint.setTextAlign(Paint.Align align);

The Paint.Align enumeration has three values: Paint.Align.LEFT, Paint.Align.CENTER, and Paint.Align.RIGHT. Depending on what alignment is set, the coordinates passed to the Canvas.drawText() method are interpreted as either the top-left corner of the rectangle, the top-center pixel of the rectangle, or the top-right corner of the rectangle. The standard alignment is Paint.Align.LEFT.

Sometimes it's also useful to know the bounds of a specific string in pixels. For this, the Paint class offers the following method:

Paint.getTextBounds(String text, int start, int end, Rect bounds);

The first argument is the string we want to get the bounds for. The second and third arguments specify the start character and the end character within the string that should be measured. The end argument is exclusive. The final argument, bounds, is a Rect instance we allocate ourselves and pass into the method. The method will write the width and height of the bounding rectangle into the Rect.right and Rect.bottom fields. For convenience we can call Rect.width() and Rect.height() to get the same values.

Note that all these methods work on a single line of text only. If we want to render multiple lines, we have to do the layout ourselves.

0 0

Post a comment