3.自定义view-TextView变色
1.效果
2.实现原理
自定义Textview,重写onDraw方法,将画布分成两部分,用不同颜色的画笔画
核心代码:
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
int middle = (int) (mProcess * getWidth());
if (mDirection == Direction.LEFT_TO_RIGHT) {
//变色区域
drawText(canvas, 0, middle, mChangePaint);
//默认区域
drawText(canvas, middle, getWidth(), mDefaultPaint);
} else {
//默认区域
drawText(canvas, 0, getWidth() - middle, mDefaultPaint);
//变色区域
drawText(canvas, getWidth() - middle, getWidth(), mChangePaint);
}
}
/**
* 裁剪画布->画文字
*
* @param canvas
* @param start
* @param end
* @param paint
*/
private void drawText(Canvas canvas, int start, int end, Paint paint) {
canvas.save();
//裁剪画布
canvas.clipRect(start, 0, end, getHeight());
String text = getText().toString();
//获取文字起点
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x = getWidth() / 2 - bounds.width() / 2;
//获取基线
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
int dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
int baseLine = getHeight() / 2 + dy;
canvas.drawText(text, x, baseLine, paint);
canvas.restore();
}