Android自定义控件drawText的baseline的问题

我们都知道Android的文本有个baseline,但是具体是什么大多数人应该都是含糊其词,用到时候位置重视感觉不能居中,我也记录一下

先看一张图:

这里写图片描述

上面有很多的标记,大家可能对基本的结构就已经清楚了,可以看到baseline的位置位于中间偏下的位置,这就是大家有时候无法居中的主要原因;

如何获取图片中的各个位置,Paint提供了方法:Paint.FontMetrics

查看代码:

public static class FontMetrics {
        /**
         * The maximum distance above the baseline for the tallest glyph in
         * the font at a given text size.
         */
        public float   top;
        /**
         * The recommended distance above the baseline for singled spaced text.
         */
        public float   ascent;
        /**
         * The recommended distance below the baseline for singled spaced text.
         */
        public float   descent;
        /**
         * The maximum distance below the baseline for the lowest glyph in
         * the font at a given text size.
         */
        public float   bottom;
        /**
         * The recommended additional space to add between lines of text.
         */
        public float   leading;
    }

可以看到里面有这么几个值;就是对应上面的值

  1. 基准点是baseline
  2. Ascent是baseline之上至字符最高处的距离
  3. Descent是baseline之下至字符最低处的距离
  4. Leading 文本件空白距离
  5. Top指的是指的是最高字符到baseline的值,即ascent的最大值
  6. 同上,bottom指的是最下字符到baseline的值,即descent的最大值

打印一下基本的值:

fontMetrics.ascent:-30.615234 descent.top:-34.853027 fontMetrics.descent:8.056641 fontMetrics.bottom:8.942871

通过打印值可以看出baseline上面的为负值baseline下面的为正值,也可以看到ascent跟top,descent跟bottom是有一定的差别的,对比上图大家应该能明白差别的原因;

上一个居中的例子:

@Override  
public void onDraw (Canvas canvas) {  
    Rect targetRect = new Rect(0, 0, 1000, 1000);  
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  
    paint.setStrokeWidth(4f);  
    paint.setTextSize(80f);  
    String testString = "Hello,world";  
    paint.setColor(Color.GRAY);  
    canvas.drawRect(targetRect, paint);  
    paint.setColor(Color.RED);  
    FontMetricsInt fontMetrics = paint.getFontMetricsInt();  
    int baseline = targetRect.top + (targetRect.bottom - targetRect.top ) / 2 - fontMetrics.top - (fontMetrics.bottom - fontMetrics.top) / 2;  
    // 下面这行是实现水平居中,drawText对应改为传入targetRect.centerX()  
    paint.setTextAlign(Paint.Align.CENTER);  
    canvas.drawText(testString, targetRect.centerX(), baseline, paint);  
}  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值