Android繪製文字時垂直置中

來源:互聯網
上載者:User

標籤: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繪製文字時垂直置中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.