Android drawText 纵向居中

protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    Paint textPaint = new Paint();
    textPaint.setARGB(200, 254, 0, 0);
    textPaint.setTextAlign(Align.CENTER);


    textPaint.setTypeface(font);
    textPaint.setTextSize(300);
    canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2  , textPaint);
}

以上代码不能将“Hello” 打印到控件的纵向居中,
要想实现纵向居中以上代码需要改为
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ; 
 //((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
//yPos 即为计算得到的“Hello“文本的baseLine的Y坐标
 canvas.drawText("Hello", xPos, yPos, textPaint);

你可能感兴趣的:(Android,技术笔记)