如图背景为黄色的TextView中的字母到上下边都有一定距离
空白是什么
经过一番搜索发现
- 文字的绘制是以一个叫做基线(baseLine)的位置为准的,而不是以View的左上角为准
- 文字的位置是受到几个值影响的,涉及到Paint.FontMetrics这个静态内部类,几个变量代表的内容也不是坐标轴上点的位置,而是以baseLine为准在Y轴方向的距离
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;
}
我们自定义一个MyTextView验证:
public class MyTextView extends android.support.v7.widget.AppCompatTextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int baseLineY = getBaseline();
int baseLineX = 0 ;
Paint paint = getPaint();
//计算各线在位置
Paint.FontMetrics fm = paint.getFontMetrics();
float ascent = baseLineY + fm.ascent;
float descent = baseLineY + fm.descent;
float top = baseLineY + fm.top;
float bottom = baseLineY + fm.bottom;
//画基线
paint.setColor(Color.GREEN);
canvas.drawLine(baseLineX, baseLineY, getMeasuredWidth(), baseLineY, paint);
//画top
paint.setColor(Color.RED);
canvas.drawLine(baseLineX, top, getMeasuredWidth(), top, paint);
//画ascent
paint.setColor(Color.BLUE);
canvas.drawLine(baseLineX, ascent, getMeasuredWidth(), ascent, paint);
//画descent
paint.setColor(Color.BLUE);
canvas.drawLine(baseLineX, descent, getMeasuredWidth(), descent, paint);
//画bottom
paint.setColor(Color.RED);
canvas.drawLine(baseLineX, bottom, getMeasuredWidth(), bottom, paint);
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<com.ax.myapplication.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff00"
android:text="Ping"
android:textColor="#000000"
android:textSize="120dp"/>
</LinearLayout>
运行效果如下
两条红线中间的黄色区域为自定义控件,字母到上下两条红线之间的距离就是平时看到的空白
为什么
在发现这个问题都时候我在想在实现TextView时为什么上下要留空白
答:为了适应不同文字在不同设备上的显示
解决办法
通过在xml布局文件中设置android:includeFontPadding=”false”可以去掉ascent到top到间距以及descent到bottom到间距,效果如下(右图为添加了属性的)
不足:这个办法虽然减小了上下边距但是仍然不能完全去除边距