android自定义View绘制的时候,会有很多情况下要与字体打交道,涉及到字体宽度、高度的时候要特别注意一下几个概念,见图:

baseLine:一行文字的底线。

Ascent: 字符顶部到baseLine的距离。

Descent: 字符底部到baseLine的距离。

Leading: 字符行间距。

public class TestOnDraw extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);MyView v = new MyView(this);this.setContentView(v);}}class MyView extends View{public MyView(Context context) {super(context);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint p = new Paint();p.setColor(Color.WHITE);p.setTextSize(50);p.setAntiAlias(true);FontMetrics fm = p.getFontMetrics();System.out.println("top = "+ fm.top);System.out.println("ascent = "+ fm.ascent);System.out.println("descent = "+ fm.descent);System.out.println("bottom = "+ fm.bottom);System.out.println("leading = "+ fm.leading);        int textHeight = (int) (Math.ceil(fm.descent - fm.ascent) + 2);        System.out.println("textHeight = "  + textHeight);                float width =500;        float baseline = 100f;        float offsetAscent = baseline + fm.ascent;        float offsetDescent = baseline +fm.descent;        float offsetTop = baseline + fm.top;        float offsetBottom = baseline + fm.bottom;                canvas.drawText("中国 bp Android", 0, baseline, p);canvas.drawLine(0, baseline, width, baseline, p);//baselinecanvas.drawLine(0, offsetAscent, width, offsetAscent, p);//ascentcanvas.drawLine(0, offsetDescent, width, offsetDescent, p);//descentcanvas.drawLine(0, offsetTop, width, offsetTop, p);//topcanvas.drawLine(0, offsetBotton, width, offsetBottom, p);//bottom}}

运行效果:


这是程序的输出结果:


得出结论: canvas drawText() 的startX是从左下角的baseline的底线开始绘画的,如果我们要得到字体的高度需要关注descent - ascent (ascent线在baseline上面,所以是负数)

更多相关文章

  1. Android第四十四期 - 登录界面的动画
  2. android XmlSerializer 组拼xml
  3. Android(安卓)Dialog自定义宽高
  4. android 完美获取状态栏高度
  5. Android动态设置控件高度
  6. Android(安卓)TextView设置一个或多个关键字的颜色
  7. android 获取实际view 宽度高度
  8. Android中动态设置布局高度一致
  9. Android(安卓)Jni NDK 打印log日志

随机推荐

  1. Android获取RecyclerView滑动距离
  2. Android通过http协议POST传输方式
  3. Android(安卓)获取屏幕尺寸与密度
  4. Android软键盘弹出,界面整体上移的问题
  5. Android之自定义ProgressBar
  6. Android对话框图片全屏
  7. Android编译系统(三):官方文档Android(安
  8. Android之解析JSON数据示例(android原生态
  9. Android中短信拦截解决方案
  10. listview圆角实现