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; }
可以看到里面有这么几个值;就是对应上面的值
- 基准点是baseline
- Ascent是baseline之上至字符最高处的距离
- Descent是baseline之下至字符最低处的距离
- Leading 文本件空白距离
- Top指的是指的是最高字符到baseline的值,即ascent的最大值
- 同上,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); }
阅读全文
1 0
- Android自定义控件drawText的baseline的问题
- android自定义控件canvas.drawText()的坐标问题
- Symbian->s60->DrawText()函数baseline 的计算
- Canvas.drawText()时,文字基线baseline的计算
- Android自定义控件中获取文字宽高的方法已经drawText中的xy
- Android自定义控件---DrawText 基线的确定
- drawText的坐标问题
- Android的DrawText详解
- Android的DrawText详解
- Android的DrawText详解
- Android的DrawText详解
- Android的DrawText,getTextBounds
- Android的DrawText详解
- Android的DrawText详解
- Android的DrawText详解
- 项目中遇到的Android drawText的一些问题
- android的drawText方法的起始点问题
- Android DrawText 字符串的绘制
- 进程间通讯(一)管道
- nginx 支持thinkphp设置
- java.lang.ExceptionInInitializerError的原因
- AspectCore.Extension.Reflection : .NET Core反射扩展库
- spring cloud+dotnet core搭建微服务架构:配置中心续(五)
- Android自定义控件drawText的baseline的问题
- 解析各类文件--cookbook读书笔记
- 开发笔记——前端优化
- 整理springdata mongodb 查询 一
- 习题1
- Android 报错解决办法:I/O error during system call, Connection reset by peer
- 小结
- OKHttp取消网络请求
- Android sendBroadcast的过程分析