In the previous example, Android ApiDemos (68): Graphics-> MeasureText describes how to obtain the size (width and height) of the drawn text string. The default alignment of text is left alignment, this example describes other Alignment Methods: Left, Center, Right, and how to draw text along any curve.
The getTextWidths method of painting gets the width of each character in the string:
[Java]
Private float [] buildTextPositions (String text,
Float y, Paint paint ){
Float [] widths = new float1;
// Initially get the widths for each char
Int n = paint. getTextWidths (text, widths );
// Now popuplate the array,
// Interleaving spaces for the Y values
Float [] pos = new float [n * 2];
Float accumulatedX = 0;
For (int I = 0; I <n; I ++ ){
Pos [I * 2 + 0] = accumulatedX;
Pos [I * 2 + 1] = y;
AccumulatedX + = widths [I];
}
Return pos;
}
Private float [] buildTextPositions (String text,
Float y, Paint paint ){
Float [] widths = new float1;
// Initially get the widths for each char
Int n = paint. getTextWidths (text, widths );
// Now popuplate the array,
// Interleaving spaces for the Y values
Float [] pos = new float [n * 2];
Float accumulatedX = 0;
For (int I = 0; I <n; I ++ ){
Pos [I * 2 + 0] = accumulatedX;
Pos [I * 2 + 1] = y;
AccumulatedX + = widths [I];
}
Return pos;
} Then draw the text in three different alignment modes: Left, Center, Right:
[Java]
P. setTextAlign (Paint. Align. LEFT );
...
P. setTextAlign (Paint. Align. CENTER );
...
P. setTextAlign (Paint. Align. RIGHT );
Canvas. drawText (TEXT_R, x, y, p );
P. setTextAlign (Paint. Align. LEFT );
...
P. setTextAlign (Paint. Align. CENTER );
...
P. setTextAlign (Paint. Align. RIGHT );
Canvas. drawText (TEXT_R, x, y, p); create a path named
[Java]
Private static void makePath (Path p ){
P. moveTo (10, 0 );
P. cubicTo (100,-50,200, 50,300, 0 );
}
Private static void makePath (Path p ){
P. moveTo (10, 0 );
P. cubicTo (100,-50,200, 50,300, 0 );
} Then draw text along the Path in three different alignment ways:
[Java]
P. setTextAlign (Paint. Align. LEFT );
...
P. setTextAlign (Paint. Align. CENTER );
...
P. setTextAlign (Paint. Align. RIGHT );
Canvas. drawPath (mPath, mPathPaint); www.2cto.com
Canvas. drawTextOnPath (TEXTONPATH, mPath, 0, 0, p );
P. setTextAlign (Paint. Align. LEFT );
...
P. setTextAlign (Paint. Align. CENTER );
...
P. setTextAlign (Paint. Align. RIGHT );
Canvas. drawPath (mPath, mPathPaint );
Canvas. drawTextOnPath (TEXTONPATH, mPath, 0, 0, p );
Author: mapdigit