码迷,mamicode.com
首页 > 移动开发 > 详细

Android绘制文字时垂直居中

时间:2017-10-02 09:36:55      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:oat   stroke   draw   str   over   line   垂直   oid   ide   

canvas.drawText(String text, float x, float y, Paint paint);

是Android中绘制文本的方法,其中的x代表文字绘制时在X轴的起始点,而y是在Y轴绘制时,文字的 baseline,不是文字的中心点也不是文字的底部。

下面代码根据绘制的Y轴中心点centerY,算出了baseline,top,bottom,ascent和descent

    @Override
    protected void onDraw(Canvas canvas) {

        int top = mPaint.getFontMetricsInt().top;
        int bottom = mPaint.getFontMetricsInt().bottom;
        int ascent = mPaint.getFontMetricsInt().ascent;
        int descent = mPaint.getFontMetricsInt().descent;

        int baselineY =centerY + (bottom-top)/2 - bottom;
        top = baselineY + top;
        bottom = baselineY + bottom;
        ascent = baselineY + ascent;
        descent = baselineY + descent;

        mPaint.setColor(Color.GREEN);
        canvas.drawText(text, 100, baselineY, mPaint);
        canvas.drawLine(0, centerY, getMeasuredWidth(), centerY, mPaint);

        mPaint.setStrokeWidth(2);

        mPaint.setColor(Color.BLACK);
        canvas.drawLine(0, top, getMeasuredWidth(), top, mPaint);

        mPaint.setColor(Color.YELLOW);
        canvas.drawLine(0, ascent, getMeasuredWidth(), ascent, mPaint);

        mPaint.setColor(Color.RED);
        canvas.drawLine(0, baselineY, getMeasuredWidth(), baselineY, mPaint);

        mPaint.setColor(Color.YELLOW);
        canvas.drawLine(0, descent, getMeasuredWidth(), descent, mPaint);

        mPaint.setColor(Color.BLACK);
        canvas.drawLine(0, bottom, getMeasuredWidth(), bottom, mPaint);

    }

 

Android绘制文字时垂直居中

标签:oat   stroke   draw   str   over   line   垂直   oid   ide   

原文地址:http://www.cnblogs.com/wenhui92/p/7618350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!