最近在項目中遇到好幾處類似下方這樣的帶單位、左大右小的布局
看起來很平常,兩個不同size的TextView左右布局,同時它們的baseline是平齊的,有人馬上就想到了在RelativeLayout中的子View可以使用layout_alignBaseline屬性完成這個布局,這里貼下xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
>
<TextView
android:id="@+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:includeFontPadding="false"
android:textColor="@color/white"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/tv_value"
android:layout_toRightOf="@id/tv_value"
android:includeFontPadding="false"
android:textColor="@color/white"
android:textSize="14sp" />
</RelativeLayout>
本來以為到這里就結束了,但是設計告訴我說,這個底邊并沒有平齊,那個kg的g明明下沉了,我要的效果不是這樣的……然后我就解釋了一下因為這個g比較特殊,你要是m就齊了,設計大哥就問了句那我要的能實現不……
這里就不得不說一下TextView的繪制了
Text的繪制
熟悉自定義view的同學應該知道,自定義view其實就是繪制文字和圖像,這就涉及到canvas的drawText()方法了,這里有好幾個重載的方法,看看我們經常常用的這個方法的源碼:
/**
* Draw the text, with origin at (x,y), using the specified paint. The
* origin is interpreted based on the Align setting in the paint.
*
* @param text The text to be drawn
* @param x The x-coordinate of the origin of the text being drawn
* @param y The y-coordinate of the baseline of the text being drawn
* @param paint The paint used for the text (e.g. color, size, style)
*/
public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags,
paint.getNativeInstance(), paint.mNativeTypeface);
}
這四個參數除了y其他的都很好理解,text是要繪制的文本內容,x是x軸方向的開始繪制的值,y參數說明里的baseline又是什么東東……
先上圖:
這張圖里有四根線,其中3就是baseline,可以看到漢字和英文字母都會超出這個線,阿拉伯數字就不會超出這個baseline。也就是說drawtext在垂直方向是以3為基準的,所以當我們想把文本垂直居中繪制在某一個view里,y的值是不能直接設為getHeight()/2的,也就是圖中的2號線,y值應該向下偏移到3的位置。
這里就說下3號線距離1號線和4號線分別對應兩個值,他們是FontMetrics這個類中的兩個值,ascent(負數)和descent的絕對值。在FontMetrics有五個float類型值:
leading 留給文字音標符號的距離
ascent 從baseline線到最高的字母頂點到距離,負值
top 從baseline線到字母最高點的距離加上ascent, |top|=|ascent|+|leading|
descent 從baseline線到字母最低點到距離
bottom 和top類似,系統為一些極少數符號留下的空間,top和bottom總會比ascent和descent大一點的就是這些少到忽略的特殊符號。
想要了解詳情的可以看看FontMetrics這個類的源碼。
所以到這里,實現平齊效果的思路就很明了,自定義一個view,繼承自View,畫兩個text即可實現,關鍵在于第二個text的baseline設置成多少。
先貼上完整的類
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
/**
* Description:
* Created by hdz on 2017/6/1.
*/
public class AlignmentView extends View {
//數值的畫筆
private Paint valuePaint;
//單位的畫筆
private Paint unitPaint;
private int valueColor = Color.BLACK;
private int unitColor = Color.BLACK;
private float valueTextSize = 30;
private float unitTextSize = 24;
//數值和單位之間的padding
private float space = 0;
/**
* 類型
* 0:下方未超出baseline
* 1:下方超出baseline
*/
private int type;
private String value;
private String unit;
//數值對應baseline的y值
private float valueDrawY;
private Paint.FontMetrics valueMetrics;
private Paint.FontMetrics unitMetrics;
public AlignmentView(Context context) {
this(context, null, 0);
}
public AlignmentView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AlignmentView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
if (attrs == null) {
return;
}
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.AlignmentView, defStyleAttr, 0);
value = array.getString(R.styleable.AlignmentView_value);
unit = array.getString(R.styleable.AlignmentView_unit);
space = array.getDimension(R.styleable.AlignmentView_space, 0);
unitColor = array.getColor(R.styleable.AlignmentView_unitColor, Color.BLACK);
valueColor = array.getColor(R.styleable.AlignmentView_valueColor, Color.BLACK);
valueTextSize = array.getDimension(R.styleable.AlignmentView_valueSize, 30);
unitTextSize = array.getDimension(R.styleable.AlignmentView_unitSize, 24);
type = array.getInt(R.styleable.AlignmentView_type, 0);
if (TextUtils.isEmpty(value)) {
value = "數值";
}
if (TextUtils.isEmpty(unit)) {
unit = "單位";
}
valuePaint = new Paint();
valuePaint.setAntiAlias(true);
valuePaint.setTextSize(valueTextSize);
valuePaint.setColor(valueColor);
valuePaint.setTextAlign(Paint.Align.LEFT);
unitPaint = new Paint();
unitPaint.setAntiAlias(true);
unitPaint.setTextSize(unitTextSize);
unitPaint.setColor(unitColor);
unitPaint.setTextAlign(Paint.Align.LEFT);
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
valueMetrics = valuePaint.getFontMetrics();
unitMetrics = unitPaint.getFontMetrics();
//獲取文字的寬高
float valueH = valueMetrics.descent - valueMetrics.ascent;
float valueW = valuePaint.measureText(value);
float unitH = unitMetrics.descent - unitMetrics.ascent;
float unitW = unitPaint.measureText(unit);
int realH = (int) (Math.max(valueH, unitH) + getPaddingBottom() + getPaddingTop());
int realW = (int) (valueW + unitW + getPaddingLeft() + getPaddingRight() + space);
int width = measureSize(realW, widthMeasureSpec);
int height = measureSize(realH, heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureSize(int defaultSize, int measureSpec) {
int resultSize = defaultSize;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
switch (mode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
break;
case MeasureSpec.EXACTLY:
resultSize = size;
break;
}
return resultSize;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawValue(canvas);
drawUnit(canvas);
canvas.drawLine(getPaddingLeft(), valueDrawY, getWidth(), valueDrawY, unitPaint);
}
// 畫左側的數值
private void drawValue(Canvas canvas) {
//y值的計算,向下偏移
valueDrawY = getHeight() / 2 + (Math.abs(valueMetrics.ascent) - valueMetrics.descent) / 2;
canvas.drawText(value, getPaddingLeft(), valueDrawY, valuePaint);
}
// 畫右側的單位
private void drawUnit(Canvas canvas) {
float valueWidth = valuePaint.measureText(value);
float x = getPaddingLeft() + valueWidth + space;
float y = valueDrawY;
if (type == 1) {
// 當底部超出baseline的時候,應該向上偏移單位對應的descent值
y = valueDrawY - unitMetrics.descent;
}
canvas.drawText(unit, x, y, unitPaint);
}
// 向外部提供設置值的方法
public void setValue(String value) {
this.value = value;
invalidate();
}
public void setUnit(String unit) {
this.unit = unit;
invalidate();
}
}
attrs:
<declare-styleable name="AlignmentView">
<attr name="value" format="string"/>
<attr name="unit" format="string"/>
<attr name="valueColor" format="color" />
<attr name="unitColor" format="color" />
<attr name="valueSize" format="dimension" />
<attr name="unitSize" format="dimension" />
<attr name="space" format="dimension"/>
<attr name="type">
<enum name="NORMAL" value="0"/>
<enum name="DESCENT_BEYOND" value="1"/>
</attr>
</declare-styleable>
這里需要說下就是drawUnit方法中drawText中的y值,當y = valueDrawY時也就達到了上面layout_alignBaseline的效果,如果還要調整,就需要
y = valueDrawY - unitMetrics.descent了,這里descent應該是unit所對應的。
布局文件
<com.example.handezhao.align.AlignmentView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#57df87"
android:padding="10dp"
app:space="5dp"
app:unitColor="#00f"
app:unitSize="20sp"
app:valueColor="#454545"
app:valueSize="40sp"
app:value="1234567890"
app:unit="abcdefghijk"
android:layout_marginTop="20dp"
app:type="DESCENT_BEYOND"
/>
最后看看兩種type的效果:
??????,這里的type可以根據不同的需求增加,比如右上角之類的……