先上效果圖再分析:
效果圖
從圖中可以看到本view支持兩種不同的類型進(jìn)度展示揪罕,一種是進(jìn)度百分比直接用textview展示,另一種加了矩形背景缸逃。第一種沒什么難度耕突,本文就以第二種為例講解一下,一步一步實(shí)現(xiàn)羡蛾,你會(huì)發(fā)現(xiàn)原來很簡單漓帅。
// 線的X起始左標(biāo)
// private float startX;
// private float endX;
//private float pading = 100f; // 左右邊距
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
startX = paintWidth+pading;
endX = width -pading;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 根據(jù) progress進(jìn)度 ,獲得X坐標(biāo)
lenth = (endX*progress/100)+startX-(progress/100*(startX));
// 底部背景線
canvas.drawLine(startX,height/2,endX,height/2,paint);
// 畫 進(jìn)度線
drawLine(canvas);
if (type==1){
// 不帶矩形的進(jìn)度
drawText(canvas);
}else if (type==2){
// 畫帶三角形的矩形進(jìn)度條
drawRecText(canvas);
}
}
首先在onSizeChanged方法中測量view寬高和線的起始位置痴怨,在onDraw方法中進(jìn)行類型判斷和根據(jù) progress進(jìn)度 獲得X坐標(biāo)忙干,然后開始畫圖。
第一步畫背景線
// 底部背景線
canvas.drawLine(startX,height/2,endX,height/2,paint);
背景
第二步 畫進(jìn)度線并實(shí)現(xiàn)動(dòng)畫效果
先畫線
canvas.drawLine(startX,height/2,lenth,height/2,mPaint);
動(dòng)畫效果
// 設(shè)置進(jìn)度
public void setProgress(int mprogress) {
ValueAnimator anim = ValueAnimator.ofFloat(0, mprogress);
anim.setDuration(3000);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
progress = (float) animation.getAnimatedValue();
invalidate();
}
});
anim.start();
}
根據(jù)ValueAnimator 獲取progress值浪藻,連續(xù)調(diào)用invalidate()進(jìn)行重繪捐迫。
bbb.gif
第三步實(shí)現(xiàn)畫矩形和內(nèi)部文字
String text =(int) progress+"%";
ttPaint.getTextBounds(text, 0, text.length(), tTextRect);
float TextHeight = tTextRect.height();
float TextWidth = tTextRect.width();
tRect.set((int)(lenth-TextWidth/2-4f),(int)(height/2-2*TextHeight-6f),(int)(lenth+TextWidth/2+4f),(int)(height/2-TextHeight));
// 畫矩形
canvas.drawRect(tRect,recPaint);
Paint.FontMetricsInt fontMetrics = ttPaint.getFontMetricsInt();
// 獲取baseLine
int baseline = tRect.top + (tRect.bottom - tRect.top - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
ttPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(text,tRect.centerX(),baseline, ttPaint);
首先獲取文本內(nèi)容寬高,然后根據(jù)文本的寬高設(shè)置矩形的初始位置爱葵,并畫出施戴,為了不讓文字緊貼矩形這里適當(dāng)調(diào)整一下矩形寬高反浓,然后在矩形的中心畫出文本內(nèi)容 。
rrrrr.gif
第四步 畫三角形
// 畫三角形
path.moveTo(lenth, (float) (height/2-0.7*TextHeight));
path.lineTo((float) (lenth-0.15*TextWidth), height / 2-TextHeight);
path.lineTo((float) (lenth+0.15*TextWidth), height / 2-TextHeight);
canvas.drawPath(path, recPaint);
path.reset();
注意: 如果你問我上邊方法的百分比為什么是0.15和0.7的話我會(huì)明確的告訴你我不知道T藁@自颉!三角型的大小需要根據(jù)矩形的大小和位置來調(diào)整肪笋,只到你認(rèn)為合適為止月劈,所以你可以隨意更改三角形的起始y坐標(biāo),連接的X坐標(biāo)也可以隨便更改涂乌,所以這里的百分比只是我自己調(diào)試看著順眼艺栈。英岭。湾盒。
eeeee.gif
項(xiàng)目地址:
csdn:http://download.csdn.net/download/qq_38367802/10172775
github:https://github.com/liuzhenhang/myview