跳至主要內容

Android paint 绘制 text

JI,XIAOYONG...大约 2 分钟

Android 中绘制文字的方法如下:

    /**
     * Draw the text, with origin at (x,y), using the specified paint. The origin is interpreted
     * based on the Align setting in the paint.
     *
     * @param text The text to be drawn
     * @param x The x-coordinate of the origin of the text being drawn
     * @param y The y-coordinate of the baseline of the text being drawn
     * @param paint The paint used for the text (e.g. color, size, style)
     */
    public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
        super.drawText(text, x, y, paint);
    }

其中y文字 baseline 的 y 坐标

下图表示Paint.FontMetrics中存储的文字的各种信息(来源:简书open in new window):

我们没法直接获取到baseline的坐标,所以只能从另外一个角度考虑:
因为在绘制文字时,文字的上下中心(即上图中的center)是确定的,我们只要计算出centerbaseline之间的偏移量,就可以计算出baseline的y坐标

又根据这个文章open in new window

基线到中线的距离 = (descent + ascent) / 2 - descent = (ascent - descent) / 2

(descent + ascent) / 2是中线 center 的值,而根据上图可知(descent + ascent) / 2 - descent的值就是 baseline 到 center 的距离。

所以

baseline的y坐标 = 文字的上下高度中心 + baseline的竖坐标和文字上下实际中心的偏移量
                = center.y + 基线到中线的距离
                = center.y + (ascent - descent) / 2

这个center.y根据场景不同可以是一行的行中心(文字在一行居中显示),或者控件的上下中心(文字在控件上下居中)

得出结论:

由于 android 绘制文字时,并不是从文字高度的中间开始绘制,而是从 baseline 开始绘制。所以在绘制文字时,为了使文字高度居中(在所指定的空间内居中,比如某一行,就在该行限定的高度内居中显示;某一控件,则整个控件的上下中间显示),需要在计算出来的文字上下中心的 y 坐标基础上加上 baseline 到文字中线的偏移量

除此之外,也可以类比得到:baseline.y = center.y + (bottom.y - top.y) / 2 - bottom.y

基线(baeseline),坡顶(ascenter),坡底(descenter)

上坡度(ascent),下坡度(descent)

行间距(leading):坡底到下一行坡顶的距离

字体的高度=上坡度+下坡度+行间距

https://blog.csdn.net/hanyongbai/article/details/84418369open in new window

参考文章:
https://www.jianshu.com/p/c1575636741eopen in new window
https://blog.csdn.net/hanyongbai/article/details/84418369open in new window
http://www.imooc.com/article/277490?block_id=tuijian_wzopen in new window
https://blog.csdn.net/xuxingxing002/article/details/50971606open in new window

文章标题:《Android paint 绘制 text》
本文作者: JI,XIAOYONG
发布时间: 2020/04/07 22:05:20 UTC+8
更新时间: 2023/12/30 16:17:02 UTC+8
written by human, not by AI
本文地址: https://jixiaoyong.github.io/blog/posts/e5860bb5.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 许可协议。转载请注明出处!
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8