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

来源:互联网 发布:taft地震波数据下载 编辑:程序博客网 时间:2024/06/05 11:02

我们都知道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);  }  
原创粉丝点击