安卓自定義View,然后drawText實(shí)現(xiàn)繪制字體
怎么實(shí)現(xiàn)垂直居中,大致效果如下:
通常會(huì)有一個(gè)text文本的區(qū)域,為了很明顯我畫了矩形,實(shí)現(xiàn)就是字體垂直居中,一開始我嘗試獲取字體高度算,但是一些api方法總是不合適,現(xiàn)在整理如下
主要是函數(shù)
private int getBaseLine(Paint paint,int centerY){
return centerY-(paint.getFontMetricsInt().bottom+paint.getFontMetricsInt().top)/2;
}
給定Paint和居中y的坐標(biāo),算出字體垂直居中的baseLine
baseline其實(shí)就是canvas.drawText(str,x,y,paint)中的y
paint.getFontMetricsInt()獲取當(dāng)前指定paint繪制字體的參數(shù)
如圖
其實(shí)一個(gè)字體都是top ascent baseLine descent bottom這樣幾根線
top ascent在baseLine上面 值是負(fù)數(shù) 絕對(duì)值是距離
那么思考獲取居中字體的baseline
centerY-字體高度/2+(字體頂部到baseLine距離)
字體高度=paint.getFontMetricsInt().bottom-paint.getFontMetricsInt().top
字體頂部到baseLine距離 -paint.getFontMetricsInt().top
centerY-(paint.getFontMetricsInt().bottom-paint.getFontMetricsInt().top)/2+( -paint.getFontMetricsInt().top)
=>centerY-(paint.getFontMetricsInt().bottom+paint.getFontMetricsInt().top)/2
咋一看還以為是centerY-字高/2,其實(shí)不是這樣的,主要是考慮想辦法拿到字體的baseLine
測(cè)試代碼如下
public class DrawTextView extends View {
private Paint mPaint;
public DrawTextView(Context context) {
super(context);
init();
}
private void init(){
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(2f);
}
private int getBaseLine(Paint paint,int centerY){
return centerY-(paint.getFontMetricsInt().bottom+paint.getFontMetricsInt().top)/2;
}
public void onDraw(Canvas canvas){
super.onDraw(canvas);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(new Rect(100,100,500,500),mPaint);
mPaint.setTextSize(25);
canvas.drawText("12345",100,getBaseLine(mPaint,(100+500)/2),mPaint);
}
}
new DrawTextView(context)調(diào)用即可看效果