Android自定义控件入门到精通--Text文本

《Android自定义控件入门到精通》文章索引 ☞ https://blog.csdn.net/Jhone_csdn/article/details/118146683

《Android自定义控件入门到精通》所有源码 ☞ https://gitee.com/zengjiangwen/Code

Text

drawText(String text, float x, float y, Paint paint)

不知道大家有没有这样的经历,在绘制文字的时候,总是把握不住绘制的精确位置,比如,我想在矩形中,居中绘制"Android"

    @Override
    protected void onDraw(Canvas canvas) {
   
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(2);
        mPaint.setTextSize(14);
        mPaint.setColor(Color.YELLOW);
        Rect rect = new Rect(10, 10, 120, 60);
        canvas.drawRect(rect, mPaint);
        //获取文字宽度
        float textWidth = mPaint.measureText("Android");
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        //获取文字高度
        float textHeight=fontMetrics.bottom-fontMetrics.top;
        float x= rect.left+(rect.width()-textWidth)/2;
        float y=rect.top+(rect.height()-textHeight)/2;
        canvas.drawText("Android",x,y,mPaint);
    }

我们预测drawText()中的x、y为开始绘制的坐标,即猜测以上代码可以实现文字水平垂直居中,但现实往往会打脸:

在这里插入图片描述

水平是居中了,但这个垂直居中有点让人摸不着头脑啊!

在前几篇中,我们绘制各种图形,都是以左上角为起始点开始绘制,为啥到了文字绘制这,不灵了呢?

还记得小学时候抄过的字母吗?

在这里插入图片描述

本子上每行的四条线,特别是红线是不是记忆尤新?

同样的,Android中Text的绘制也有对应的四条线

    @Override
    protected void onDraw(Canvas canvas) {
   
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(1);
        mPaint.setColor(Color.YELLOW);
        mPaint.setTextSize(48);//设置文字大小为12像素
        String text = "abcdefghijklmnopqrst";
        float textWidth = mPaint.measureText(text);
        int x = 100, y = 100;
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float top = fontMetrics.top;
        float ascent = fontMetrics.ascent;
        float descent = fontMetrics.descent;
        float bottom = fontMetrics.bottom;
        mPaint.setColor(Color.YELLOW);
        canvas.drawLine(x, top + y, x + textWidth, top + y, mPaint);
        mPaint.setColor(Color.RED);
        canvas.drawLine(x, ascent + y, x + textWidth, ascent + y, mPaint)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一鱼浅游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值