Android编程之绘制文本(FontMetrics)实现方法

时间:2021-05-20

本文实例讲述了Android编程之绘制文本(FontMetrics)实现方法。分享给大家供大家参考,具体如下:

Canvas 作为绘制文本时,使用FontMetrics对象,计算位置的坐标。

它的思路和java.awt.FontMetrics的基本相同。

FontMetrics对象

它以四个基本坐标为基准,分别为:

FontMetrics.top
FontMetrics.ascent
FontMetrics.descent
FontMetrics.bottom

该图片将如下

代码如下:

Paint textPaint = new Paint( Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize( 35); textPaint.setColor( Color.WHITE); // FontMetrics对象 FontMetrics fontMetrics = textPaint.getFontMetrics(); String text = "abcdefghijklmnopqrstu"; // 计算每一个坐标 float baseX = 0; float baseY = 100; float topY = baseY + fontMetrics.top; float ascentY = baseY + fontMetrics.ascent; float descentY = baseY + fontMetrics.descent; float bottomY = baseY + fontMetrics.bottom; // 绘制文本 canvas.drawText( text, baseX, baseY, textPaint); // BaseLine描画 Paint baseLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG);> baseLinePaint.setColor( Color.RED); canvas.drawLine(0, baseY, getWidth(), baseY, baseLinePaint); // Base描画 canvas.drawCircle( baseX, baseY, 5, baseLinePaint); // TopLine描画 Paint topLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); topLinePaint.setColor( Color.LTGRAY); canvas.drawLine(0, topY, getWidth(), topY, topLinePaint); // AscentLine描画 Paint ascentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); ascentLinePaint.setColor( Color.GREEN); canvas.drawLine(0, ascentY, getWidth(), ascentY, ascentLinePaint); // DescentLine描画 Paint descentLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); descentLinePaint.setColor( Color.YELLOW); canvas.drawLine(0, descentY, getWidth(), descentY, descentLinePaint); // ButtomLine描画 Paint bottomLinePaint = new Paint( Paint.ANTI_ALIAS_FLAG); bottomLinePaint.setColor( Color.MAGENTA); canvas.drawLine(0, bottomY, getWidth(), bottomY, bottomLinePaint);

希望本文所述对大家Android程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章