zoukankan      html  css  js  c++  java
  • Android字体度量(FontMetrics)

    基本概念
    字体的度量,是指对于指定字号的某种字体,在度量方面的各种属性,其描述参数包括:

        baseline:字符基线
        ascent:字符最高点到baseline的推荐距离
        top:字符最高点到baseline的最大距离
        descent:字符最低点到baseline的推荐距离
        bottom:字符最低点到baseline的最大距离
        leading:行间距,即前一行的descent与下一行的ascent之间的距离

    参照下面这些图来帮助理解上述概念:
                  



    相关属性获取与调整
    1. 字符属性参数
         API中的Paint.FontMetrics(Int)类,定义了字符的ascent、top、descent和bottom,可以用来获取对应字符的相应参数,如下表:
    Fields
    public float     ascent     The recommended distance above the baseline for singled spaced text.
    public float     bottom     The maximum distance below the baseline for the lowest glyph in the font at a given text size.
    public float     descent     The recommended distance below the baseline for singled spaced text.
    public float     leading     The recommended additional space to add between lines of text.
    public float     top     The maximum distance above the baseline for the tallest glyph in the font at a given text size.
         注意,以上获取到的属性值,是相对于baseline的坐标值,而不是距离值。
         字体的高度可以通过descent+Math.abs(ascent)计算得到。字符串的宽度可以通过Paint.measureText("xxxx")得到。注意,如果所选字体为等宽字体,则每个字符的宽度相等,如果非等宽字体,则字符宽度并不相同。
         字符串的实际可视高度和宽度,即最小包围框则可以通过Paint.getTextBounds()或者TextView.getLineBounds()获得。

    2. 行间距(leading)
         对于TextView的行间距调整设置,可以使用 setLineSpacing(add, mult) 方法,或者在布局文件中使用属性 lineSpacingExtra 或者 lineSpacingMultiplier 进行定义。
         对于Paint绘制的Text的行间距调整,可以使用Paint.fontMetrics中的 leading 属性字段进行定义。

    3. 行高
         字符所在行的高度 = ascent + descent + leading,即字符的高度+行间距,可以通过descent+Math.abs(ascent) + leading计算得到。
         对于TextView中的行高,可以直接通过getLineHeight()方法获取。

    4. 字符间距(kerning)
         对于textView 和 Paint绘制的Text,可以分别使用各自类中的 getLetterSpacing() 和 setLetterSpacing() 方法获取和设置字符间距,对于TextView还可以在布局文件中使用属性 letterSpacing 进行定义。
         注意以上的方法和属性是在API 21引入的,对于之前的版本,只能通过 SpannableString类 及相应的方法来间接调整。



    参考与阅读
    0. Code-GitHub

    1. Android开发者文档--android.graphics.Paint.FontMetrics
    2. Android开发者文档--android.graphics.Paint.FontMetricsInt
    3. Android开发者文档--android.widget.TextView
    4. Android开发者文档--android.graphics.Paint
    5. Android开发者文档--android.text.SpannableString
    6. Android字符串进阶之三:字体属性及测量(FontMetrics)

    7. style the android fonts styles with leading and tracking
    8. How to adjust text kerning in Android TextView(API 21 之前版本,SpannableString方法)

  • 相关阅读:
    常用模块Part(1)
    递归函数
    python 生成器函数
    python 迭代器与生成器
    python 函数进阶
    python 装饰器进阶
    python time模块
    python 初始函数
    python 文件操作
    python 一些小知识
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/12874981.html
Copyright © 2011-2022 走看看