¿Cómo alinear el texto verticalmente?
Objetivo: Android> = 1.6 en un Canvas puro.
Supongamos que quiero escribir una función que dibuje un rectángulo rojo grande (ancho, alto) y luego dibuje un negroHola Mundo Texto dentro. Quiero que el texto esté visualmente en el centro del rectángulo. Entonces intentemos:
void drawHelloRectangle(Canvas c, int topLeftX,
int topLeftY, int width, int height) {
Paint mPaint = new Paint();
// height of 'Hello World'; height*0.7 looks good
int fontHeight = (int)(height*0.7);
mPaint.setColor(COLOR_RED);
mPaint.setStyle(Style.FILL);
c.drawRect( topLeftX, topLeftY, topLeftX+width, topLeftY+height, mPaint);
mPaint.setTextSize(fontHeight);
mPaint.setColor(COLOR_BLACK);
mPaint.setTextAlign(Align.CENTER);
c.drawText( "Hello World", topLeftX+width/2, ????, mPaint);
}
Ahora no sé qué poner en el argumento de drawText marcado por????
, es decir, no sé cómo alinear verticalmente el texto.
Algo como
???? = topLeftY + height / 2 + fontHeight / 2 - fontHeight / 8;
parece funcionar más o menos bien, pero debe haber una mejor manera.