Como alinhar o texto verticalmente?
Alvo: Android> = 1,6 em uma tela pura.
Suponha que eu queira escrever uma função que desenhe um retângulo vermelho grande (largura, altura) e depois desenhe um pretoOlá Mundo texto para dentro. Quero que o texto esteja visualmente no centro do retângulo. Então vamos tentar:
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);
}
Agora não sei o que colocar no argumento do drawText marcado por????
, ou seja, não sei como alinhar verticalmente o texto.
Algo como
???? = topLeftY + height / 2 + fontHeight / 2 - fontHeight / 8;
parece funcionar mais ou menos ok, mas deve haver uma maneira melhor.