android 自定义文本 文字居中

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);


Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Style.STROKE);
paint.setTextSize(50);
canvas.drawText("hl 你",(getWidth() - getFontWidth(paint,"hellow"))/2, (getHeight()- getFontHeight(paint))/3 *2, paint);

View pView = (View) getParent();
pL = pView.getLeft();
pR = pView.getRight();
pT = pView.getTop();
pB = pView.getBottom();
}

public float getFontWidth(Paint paint, String text) {
    return paint.measureText(text);
}


/**
* @return 返回指定的文字高度
*/
public float getFontHeight(Paint paint) {
    FontMetrics fm = paint.getFontMetrics();
    //文字基准线的下部距离-文字基准线的上部距离 = 文字高度
    return fm.descent - fm.ascent ;
}

猜你喜欢

转载自blog.csdn.net/u010792039/article/details/80097660