今天有點(diǎn)時(shí)間,跟著大牛們學(xué)習(xí)了下自定義textview琼懊,實(shí)現(xiàn)文字變色,效果如下:
device-2017-06-25-161933.gif
上面效果實(shí)現(xiàn)的大致的思路為:
1:寫一個(gè)類爬早,繼承自textview哼丈,這里繼承自view也可以,不過繼承自textview的話筛严,只需要重寫onDraw()方法就可以了醉旦,同時(shí)可以使用textview的getText()等方法,代碼邏輯上就要少些處理桨啃;
2:根據(jù)需要自定義一些屬性车胡,并初始這些屬性;
3:初始化畫筆照瘾,這里需要初始化兩個(gè)畫筆吨拍,一個(gè)是變色的畫筆,另一個(gè)是不變色的畫筆网杆,并設(shè)置好相應(yīng)的屬性;
4:重寫onDraw()方法,進(jìn)行繪制
繼承textview時(shí)實(shí)現(xiàn)的那三個(gè)構(gòu)造方法什么時(shí)候調(diào)用在上篇播客中說了碳却,這里就不說了队秩,直接對(duì)畫筆進(jìn)行初始化;
private Paint getPaintByColor(int color) {
Paint paint = new Paint();
//設(shè)置顏色
paint.setColor(color);
//設(shè)置抗鋸齒
paint.setAntiAlias(true);
//設(shè)置防抖動(dòng)
paint.setDither(true);
//設(shè)置字體大小
paint.setTextSize(getTextSize());
return paint;
}
根據(jù)傳入的顏色返回一個(gè)Paint對(duì)象昼浦;接下來就是在onDraw()方法中進(jìn)行繪制馍资;
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
//根據(jù)進(jìn)度計(jì)算中間值
int middle = (int) (mCurrentProgres * getWidth());
//從左到右繪制
if(mDirection==Direction.LEFT_TO_RIGHT){
//右邊是紅色左邊是黑色
drawText(canvas, changePaint, 0, middle);
drawText(canvas, originPaint, middle, getWidth());
}else{
drawText(canvas, changePaint, getWidth()-middle, getWidth());
drawText(canvas, originPaint, 0, getWidth()-middle);
}
}
在這里要將super.onDraw(canvas);注釋掉,自己去實(shí)現(xiàn)繪制关噪,如果沒有注釋掉就會(huì)調(diào)用TextView的onDraw方法將文字繪制出來鸟蟹;首先需要計(jì)算出文字的中間值,根據(jù)計(jì)算出來的中間值可以確定變色的繪制的end位置和不變色繪制的start開始位置使兔,因?yàn)閷?shí)現(xiàn)的是從左到右或者從右到左的變色建钥,所有要定義兩個(gè)方式并初始化值;
//實(shí)現(xiàn)不同朝向變色
private Direction mDirection=Direction.LEFT_TO_RIGHT;
public enum Direction{
LEFT_TO_RIGHT,RIGHT_TO_LEFT;
}
在繪制的時(shí)候其實(shí)還是對(duì)Paint和Canvas的使用虐沥;調(diào)用Canvas的
//保存畫布
canvas.save();
方法保存畫布熊经,接著調(diào)用Canvas的
Rect rt = new Rect(start, 0, end, getHeight());
canvas.clipRect(rt);
方法進(jìn)行變色和不變色區(qū)域的裁剪,跟著就使用Paint畫筆進(jìn)行繪制了欲险;
String text = getText().toString();
//獲取字體的寬度
Rect rect = new Rect();
paint.getTextBounds(text, 0, text.length(), rect);
int x = getWidth() / 2 - rect.width() / 2;
//基線
Paint.FontMetricsInt metricsInt = paint.getFontMetricsInt();
int dy = (metricsInt.bottom - metricsInt.top) / 2 - metricsInt.bottom;
int baseLine = getHeight() / 2 + dy;
canvas.drawText(text, x, baseLine, paint);
繪制完后要記得重置畫布镐依,
//釋放畫布
canvas.restore();
這樣就繪制完成了,在調(diào)用的地方設(shè)置相應(yīng)的一些動(dòng)畫效果就可以了天试,
/**
* 設(shè)置屬性動(dòng)畫
* @param direction
*/
private void setAnimator(ColorTextView.Direction direction){
colorText.setDirection(direction);
ValueAnimator animator = ObjectAnimator.ofFloat(0, 1);
animator.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
colorText.setCurrentProgress(animatedValue);
}
});
animator.start();
}