Android TextView 高度問題

前言:java

在咱們作界面開發的時候,UI的標註圖中常常是標註了文字的字號和文件的間距。而當咱們使用多個TextView 實現後,卻發現textView 之間的空白區域的高度,是遠大於設計標註的。canvas

前提: TextView height = warp_content。 設爲單行。ide

緣由: TextView 高度包含 1) IncludedFontPadding  2,Line height;spa

而LineHeight 也並非文字字號高度,而且也大於字號高度。.net

TextView textView = (TextView) findViewById(R.id.sample_text);
        textView.setBackgroundColor(Color.YELLOW);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX , 60);

1,關於行高獲取:設計

int ht = textView.getLineHeight();

這個高度的獲取,並不須要對當前的Text 進行測量。 與當前的TextSize 正相關。code

2,對象

textView.setIncludeFontPadding(false);

能夠經過這個方法,禁掉首行文字和末行文字的font padding。blog

3, 關於文字繪製與行高開發

public class MText extends TextView{
    public MText(Context context) {
        super(context);
    }

    public MText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

// FontMetrics對象
        Paint textPaint = getPaint();
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();

// 計算每個座標
        float baseX = 0;
        float baseY = getBaseline();
        float topY = baseY + fontMetrics.top;
        float ascentY = baseY + fontMetrics.ascent;
        float descentY = baseY + fontMetrics.descent;
        float bottomY = baseY + fontMetrics.bottom;

// 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);

    }
}

文字的行高計算:

float ascentY = baseY + fontMetrics.ascent;
float descentY = baseY + fontMetrics.descent;

int lineHeght = descentY - ascentY; //[不是從源碼得出的結論,待進一步驗證]

 

 

參考:

https://blog.csdn.net/l732427480/article/details/51711970

相關文章
相關標籤/搜索