Android DrawText 基线的确定问题

来源:互联网 发布:matlab 2017b mac 编辑:程序博客网 时间:2024/05/01 22:27

在自定义控件的时候,有时候会用到DrawText 方法

  • @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)

x,y 分别表示 基线的开始坐标,并不是 文字左上角的坐标,因为文字的绘制是以基线为基础的

这里写图片描述
图中的 五角星 所在的线 就是基线 BaseLine

那么如何确定基线的x,y坐标呢

需要借助 Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
FontMetricsInt 类 有 top 、bottom 两个成员,
top表示基线到文字最上面的位置的距离 是个负值 bottom为基线到最下面的距离,为正值

如果想要基于一个位置竖直居中,那么居中的位置 坐标假设为 centerY

baseLineY = centerY - (fm.bottom-fm.top)/2- fm.top;

这样就可以确定基线的坐标

所以只需要修改centerY的位置 就可以基于这个位置居中了

或者 比如想在 top 到 bottom 之间竖直居中 那么center = (bottom-top)/2;
baseLineY = (bottom-top)/2 - (fm.bottom-fm.too)/2 - fm.top=
(bottom+top-fm.bottom-fm.top)/2;

最后 不要忘记在 paint.getFontMetricsInt(); 之前设置一下字体大小哦

0 0
原创粉丝点击