最近在項(xiàng)目中遇到好幾處類似下方這樣的帶單位彩倚、左大右小的布局
看起來很平常,兩個(gè)不同size的TextView左右布局扶平,同時(shí)它們的baseline是平齊的帆离,有人馬上就想到了在RelativeLayout中的子View可以使用layout_alignBaseline屬性完成這個(gè)布局,這里貼下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>
本來以為到這里就結(jié)束了结澄,但是設(shè)計(jì)告訴我說哥谷,這個(gè)底邊并沒有平齊岸夯,那個(gè)kg的g明明下沉了,我要的效果不是這樣的……然后我就解釋了一下因?yàn)檫@個(gè)g比較特殊们妥,你要是m就齊了囱修,設(shè)計(jì)大哥就問了句那我要的能實(shí)現(xiàn)不……
這里就不得不說一下TextView的繪制了
Text的繪制
熟悉自定義view的同學(xué)應(yīng)該知道,自定義view其實(shí)就是繪制文字和圖像王悍,這就涉及到canvas的drawText()方法了,這里有好幾個(gè)重載的方法餐曼,看看我們經(jīng)常常用的這個(gè)方法的源碼:
/**
* 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);
}
這四個(gè)參數(shù)除了y其他的都很好理解压储,text是要繪制的文本內(nèi)容,x是x軸方向的開始繪制的值源譬,y參數(shù)說明里的baseline又是什么東東……
先上圖:
這張圖里有四根線集惋,其中3就是baseline,可以看到漢字和英文字母都會超出這個(gè)線踩娘,阿拉伯?dāng)?shù)字就不會超出這個(gè)baseline刮刑。也就是說drawtext在垂直方向是以3為基準(zhǔn)的,所以當(dāng)我們想把文本垂直居中繪制在某一個(gè)view里养渴,y的值是不能直接設(shè)為getHeight()/2的雷绢,也就是圖中的2號線,y值應(yīng)該向下偏移到3的位置理卑。
這里就說下3號線距離1號線和4號線分別對應(yīng)兩個(gè)值翘紊,他們是FontMetrics這個(gè)類中的兩個(gè)值,ascent(負(fù)數(shù))和descent的絕對值藐唠。在FontMetrics有五個(gè)float類型值:
leading 留給文字音標(biāo)符號的距離
ascent 從baseline線到最高的字母頂點(diǎn)到距離帆疟,負(fù)值
top 從baseline線到字母最高點(diǎn)的距離加上ascent, |top|=|ascent|+|leading|
descent 從baseline線到字母最低點(diǎn)到距離
bottom 和top類似宇立,系統(tǒng)為一些極少數(shù)符號留下的空間踪宠,top和bottom總會比ascent和descent大一點(diǎn)的就是這些少到忽略的特殊符號。
想要了解詳情的可以看看FontMetrics這個(gè)類的源碼妈嘹。
所以到這里柳琢,實(shí)現(xiàn)平齊效果的思路就很明了,自定義一個(gè)view润脸,繼承自View染厅,畫兩個(gè)text即可實(shí)現(xiàn),關(guān)鍵在于第二個(gè)text的baseline設(shè)置成多少津函。
先貼上完整的類
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 {
//數(shù)值的畫筆
private Paint valuePaint;
//單位的畫筆
private Paint unitPaint;
private int valueColor = Color.BLACK;
private int unitColor = Color.BLACK;
private float valueTextSize = 30;
private float unitTextSize = 24;
//數(shù)值和單位之間的padding
private float space = 0;
/**
* 類型
* 0:下方未超出baseline
* 1:下方超出baseline
*/
private int type;
private String value;
private String unit;
//數(shù)值對應(yīng)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 = "數(shù)值";
}
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);
}
// 畫左側(cè)的數(shù)值
private void drawValue(Canvas canvas) {
//y值的計(jì)算肖粮,向下偏移
valueDrawY = getHeight() / 2 + (Math.abs(valueMetrics.ascent) - valueMetrics.descent) / 2;
canvas.drawText(value, getPaddingLeft(), valueDrawY, valuePaint);
}
// 畫右側(cè)的單位
private void drawUnit(Canvas canvas) {
float valueWidth = valuePaint.measureText(value);
float x = getPaddingLeft() + valueWidth + space;
float y = valueDrawY;
if (type == 1) {
// 當(dāng)?shù)撞砍鯾aseline的時(shí)候,應(yīng)該向上偏移單位對應(yīng)的descent值
y = valueDrawY - unitMetrics.descent;
}
canvas.drawText(unit, x, y, unitPaint);
}
// 向外部提供設(shè)置值的方法
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值尔苦,當(dāng)y = valueDrawY時(shí)也就達(dá)到了上面layout_alignBaseline的效果涩馆,如果還要調(diào)整行施,就需要
y = valueDrawY - unitMetrics.descent了,這里descent應(yīng)該是unit所對應(yīng)的魂那。
布局文件
<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可以根據(jù)不同的需求增加,比如右上角之類的……