android FontMetrics中各个字段的意义

本文深入解析了FontMetrics类的五个关键变量:top、ascent、descent、bottom和leading,阐述了它们在文本布局和绘制中的作用,尤其强调了在Android环境中如何影响文字的垂直定位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FontMetrics类的定义如下:

/**
     * Class that describes the various metrics for a font at a given text size.
     * Remember, Y values increase going down, so those values will be positive,
     * and values that measure distances going up will be negative. This class
     * is returned by getFontMetrics().
     */
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;
}

用下图表示这5个变量的意思:
在这里插入图片描述

  • Baseline是基线,在Android中,文字的绘制都是从Baseline处开始的

  • leading(行间距)则表示上一行字符的descent到该行字符的ascent之间的距离;

  • top和bottom文档描述地很模糊,其实这里我们可以借鉴一下TextView对文本的绘制,TextView在绘制文本的时候总会在文本的最外层留出一些内边距,为什么要这样做?因为TextView在绘制文本的时候考虑到了类似读音符号,下图中的A上面的符号就是一个拉丁文的类似读音符号的东西:
    在这里插入图片描述
    top的意思其实就是除了Baseline到字符顶端的距离外还应该包含这些符号的高度,bottom的意思也是一样。在TextView中我们可以通过xml设置其属性android:includeFontPadding="false"去掉一定的边距值但是不能完全去掉。

参考:

  1. 用TextPaint来绘制文字. https://www.cnblogs.com/tianzhijiexian/p/4297664.html
  2. 聊一聊Paint.FontMetrics.descent和Paint.FontMetrics.ascent那些事. https://www.jianshu.com/p/7a29d171327f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值