Android實現(xiàn)下載進度條效果
最終效果和對比vivo商店效果
vivo應用商店下載效果:

最終實現(xiàn)效果:

分析1 - 計算進度
進度計算就比較簡單了,我們通過復寫onSizeChanged()方法,獲取到控件的寬后,先計算當前進度百分比,再將百分比乘以寬度,就可以得到應該繪制的寬度了。
繪制圓角矩形需要傳一個Rect,Rect的構造方法需要傳4個位置,分別是left、top、right、bottom,我們主要是計算不斷變化的right值。在drawProgress()方法中,right值為最大的寬度 * 進度百分比值。
/**
* 控件寬
*/
private int mViewWidth;
/**
* 控件高
*/
private int mViewHeight;
/**
* 圓角弧度
*/
private float mRadius;
/**
* 當前進度
*/
private int mProgress;
/**
* 最大進度值
*/
private int mMaxProgress;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//畫進度條
drawProgress(canvas);
}
/**
* 畫進度
*/
private void drawProgress(Canvas canvas) {
RectF rect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom());
canvas.drawRect(rect, mProgressPaint);
}
/**
* 獲取當前進度值比值
*/
private float getProgressRatio() {
return (mProgress / (mMaxProgress * 1.0f));
}
//------------ getFrameXxx()方法都是處理padding ------------
private float getFrameLeft() {
return getPaddingStart();
}
private float getFrameRight() {
return mViewWidth - getPaddingEnd();
}
private float getFrameTop() {
return getPaddingTop();
}
private float getFrameBottom() {
return mViewHeight - getPaddingBottom();
}
//------------ getFrameXxx()方法都是處理padding ------------
分析2 - 繪制圓角矩形
背景和進度條,都是圓角矩形,我們可以使用canvas.drawRoundRect()的API來繪制。但是使用canvas.drawRoundRect()會有個問題,當進度比較小的時候,例如1%,計算出來的矩形長度比較小,會導致圓角不是滿的,缺陷效果見動圖(注意看剛從左側出來時圓角的大小)。

public class DownloadProgressView extends View {
...省略其他代碼
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
//計算出圓角半徑
mRadius = Math.min(mViewWidth, mViewHeight) / 2f;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//畫背景
drawBg(canvas);
//畫進度條
drawProgress(canvas);
}
/**
* 畫背景
*/
private void drawBg(Canvas canvas) {
canvas.drawRoundRect(new RectF(getFrameLeft(), getPaddingTop(), getFrameRight(), getFrameBottom()), mRadius, mRadius, mBgPaint);
}
/**
* 畫進度
*/
private void drawProgress(Canvas canvas) {
RectF rect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom());
canvas.drawRoundRect(rect, mRadius, mRadius, mProgressPaint);
}
//------------ getFrameXxx()方法都是處理padding ------------
private float getFrameLeft() {
return getPaddingStart();
}
private float getFrameRight() {
return mViewWidth - getPaddingEnd();
}
private float getFrameTop() {
return getPaddingTop();
}
private float getFrameBottom() {
return mViewHeight - getPaddingBottom();
}
//------------ getFrameXxx()方法都是處理padding ------------
}
解決方案
我的方案是這樣的,不使用drawRoundRect()方法來繪制圓角矩形,而是先使用canvas.clipPath()方法,添加一個有圓角矩形的Path,來裁切畫布,再drawRect()方法來繪制一個長矩形,就保持了圓角。
但clipPath()也有一個缺點,就是裁切出來的圓角會有鋸齒,Paint設置了setAntiAlias(true)也沒有用,大家有好的方法,互相學習一下!
public class DownloadProgressView extends View {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//裁剪圓角
clipRound(canvas);
//畫背景
drawBg(canvas);
//畫進度條
drawProgress(canvas);
}
/**
* 裁剪圓角
*/
private void clipRound(Canvas canvas) {
Path path = new Path();
RectF roundRect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight(), getFrameBottom());
path.addRoundRect(roundRect, mRadius, mRadius, Path.Direction.CW);
canvas.clipPath(path);
}
/**
* 畫背景
*/
private void drawBg(Canvas canvas) {
canvas.drawRect(new RectF(getFrameLeft(), getPaddingTop(), getFrameRight(), getFrameBottom()), mBgPaint);
}
/**
* 畫進度
*/
private void drawProgress(Canvas canvas) {
RectF rect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom());
canvas.drawRect(rect, mProgressPaint);
}
}
分析3 - 繪制文字和交匯
要讓文字和進度交匯時,讓藍色變?yōu)榘咨枰褂玫絇orterDuffXfermode。PorterDuffXfermode可以將2個圖像進行合成,或者簡單說為相交模式,而合成方式有16種,見下圖。(Src藍色方塊為上層圖層,Dst黃色圓形為下層圖層。)

查閱文檔,我們發(fā)現(xiàn)SrcATop模式比較符合我們的需求,在SrcATop模式下,Src圖層不覆蓋Dst圖層的像素會被拋棄,只保留Src圖層覆蓋Dst圖層的圖層像素。
我們的思路是這樣的:畫4個圖層,最底部的灰色背景圖層,再上一層藍色進度圖層,接著是文字圖層,最上層是一層白色的進度圖層,重點在畫文字和白色進度圖層是添加了PorterDuffXfermode(SrcATop模式)。
白色進度和藍色進度的大小一直是同步的,但是因為PorterDuffXfermode的原因,白色圖層未覆蓋到文字時,一直都是被拋棄圖層像素,相當于是透明的,只有當和文字相交時,才會繪制出白色圖層,就顯示出了一半白色文字,一半藍色文字的效果,而其他部分都沒有和文字相交都被拋棄,都為透明。
繪制文字、白色進度圖層代碼,見drawText()方法。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//裁剪圓角
clipRound(canvas);
//畫背景
drawBg(canvas);
//畫進度條
drawProgress(canvas);
//畫文字圖層
drawText(canvas);
}
/**
* 畫文字
*/
private void drawText(Canvas canvas) {
mTextPaint.setColor(mPercentageTextColor);
//創(chuàng)建文字圖層
Bitmap textBitmap = Bitmap.createBitmap(mViewWidth, mViewHeight, Bitmap.Config.ARGB_8888);
Canvas textCanvas = new Canvas(textBitmap);
String textContent = mProgress + "%";
//計算文字Y軸坐標
float textY = mViewHeight / 2.0f - (mTextPaint.getFontMetricsInt().descent / 2.0f + mTextPaint.getFontMetricsInt().ascent / 2.0f);
textCanvas.drawText(textContent, mViewWidth / 2.0f, textY, mTextPaint);
//畫最上層的白色圖層,未相交時不會顯示出來
mTextPaint.setColor(mPercentageTextColor2);
mTextPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
textCanvas.drawRect(new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom()), mTextPaint);
//畫結合后的圖層
canvas.drawBitmap(textBitmap, getFrameLeft(), getFrameTop(), mTextPaint);
mTextPaint.setXfermode(null);
textBitmap.recycle();
}
手勢拓展
經過上面的進度、文字、交匯處理,進度條算是完整了,接下來拓展一下沒有的東西,例如手勢拖動,就像SeekBar一樣,當我們觸摸進度條時,進度會隨著移動而改變進度。
我們先重寫dispatchTouchEvent()方法,當down事件來到時,讓父控件不攔截,我們進行攔截。接著重寫onTouchEvent()方法,計算Move、Up時,移動的距離,計算出百分比和應有的進度值,然后不斷調用setProgress()來更新進度。
public class DownloadProgressView extends View {
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
//攔截事件,然后讓父類不進行攔截
if (mControlMode == MODE_TOUCH && action == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
return true;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//拽托模式下才起效果
if (mControlMode == MODE_TOUCH) {
int action = event.getAction();
//包裹Down事件時的x坐標
if (action == MotionEvent.ACTION_DOWN) {
mTouchDownX = event.getX();
return true;
} else if (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_UP) {
//Move或Up的時候,計算拽托進度
float endX = event.getX();
//計算公式:百分比值 = 移動距離 / 總長度
float distanceX = Math.abs(endX - mTouchDownX);
float ratio = (distanceX * 1.0f) / (getFrameRight() - getFrameLeft());
//計算百分比應該有的進度:進度 = 總進度 * 進度百分比值
float progress = mMaxProgress * ratio;
setProgress((int) progress);
return true;
}
return super.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
}
完整代碼
自定義屬性
<resources>
<declare-styleable name="DownloadProgressView">
<!-- 進度條背景 -->
<attr name="dpv_bg" format="color" />
<!-- 已有進度條背景 -->
<attr name="dpv_progress_bg" format="color" />
<!-- 百分比字體顏色 -->
<attr name="dpv_percentage_text_color" format="color" />
<!-- 上層百分比字體顏色 -->
<attr name="dpv_percentage_text_color2" format="color" />
<attr name="dpv_percentage_text_size" format="integer|float|dimension|reference" />
<!-- 當前進度值 -->
<attr name="dpv_progress" format="integer" />
<!-- 最大進度值 -->
<attr name="dpv_max_progress" format="integer" />
<!-- 控制模式 -->
<attr name="dpv_control_mode" format="enum">
<enum name="normal" value="1" />
<enum name="touch" value="2" />
</attr>
</declare-styleable>
</resources>
自定義View
public class DownloadProgressView extends View {
/**
* 控制模式-普通
*/
private static final int MODE_NORMAL = 1;
/**
* 控制模式-觸摸
*/
private static final int MODE_TOUCH = 2;
/**
* View默認最小寬度
*/
private int mDefaultMinWidth;
/**
* View默認最小高度
*/
private int mDefaultMinHeight;
/**
* 控件寬
*/
private int mViewWidth;
/**
* 控件高
*/
private int mViewHeight;
/**
* 圓角弧度
*/
private float mRadius;
/**
* 背景畫筆
*/
private Paint mBgPaint;
/**
* 進度畫筆
*/
private Paint mProgressPaint;
/**
* 文字畫筆
*/
private Paint mTextPaint;
/**
* 當前進度
*/
private int mProgress;
/**
* 背景顏色
*/
private int mBgColor;
/**
* 進度背景顏色
*/
private int mProgressBgColor;
/**
* 進度百分比文字的顏色
*/
private int mPercentageTextColor;
/**
* 第二層進度百分比文字的顏色
*/
private int mPercentageTextColor2;
/**
* 進度百分比文字的字體大小
*/
private float mPercentageTextSize;
/**
* 最大進度值
*/
private int mMaxProgress;
/**
* 進度更新監(jiān)聽
*/
private OnProgressUpdateListener mOnProgressUpdateListener;
/**
* 控制模式
*/
private int mControlMode;
/**
* 按下時Down事件的x坐標
*/
private float mTouchDownX;
public DownloadProgressView(Context context) {
this(context, null);
}
public DownloadProgressView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DownloadProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
initAttr(context, attrs, defStyleAttr);
//取消硬件加速
setLayerType(LAYER_TYPE_SOFTWARE, null);
//背景畫筆
mBgPaint = new Paint();
mBgPaint.setAntiAlias(true);
mBgPaint.setColor(mBgColor);
//進度畫筆
mProgressPaint = new Paint();
mProgressPaint.setColor(mProgressBgColor);
mProgressPaint.setAntiAlias(true);
//文字畫筆
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(mPercentageTextSize);
mTextPaint.setTextAlign(Paint.Align.CENTER);
//計算默認寬、高
mDefaultMinWidth = dip2px(context, 180f);
mDefaultMinHeight = dip2px(context, 40f);
}
private void initAttr(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.DownloadProgressView, defStyleAttr, 0);
mBgColor = array.getColor(R.styleable.DownloadProgressView_dpv_bg, Color.argb(100, 169, 169, 169));
mProgressBgColor = array.getColor(R.styleable.DownloadProgressView_dpv_progress_bg, Color.GRAY);
//進度百分比文字的顏色,默認和進度背景顏色一致
mPercentageTextColor = array.getColor(R.styleable.DownloadProgressView_dpv_percentage_text_color, mProgressBgColor);
//第二層,進度百分比文字的顏色
mPercentageTextColor2 = array.getColor(R.styleable.DownloadProgressView_dpv_percentage_text_color2, Color.WHITE);
//進度百分比文字的字體顏色
mPercentageTextSize = array.getDimension(R.styleable.DownloadProgressView_dpv_percentage_text_size, sp2px(context, 15f));
//當前進度值
mProgress = array.getInt(R.styleable.DownloadProgressView_dpv_progress, 0);
//最大進度值
mMaxProgress = array.getInteger(R.styleable.DownloadProgressView_dpv_max_progress, 100);
//控制模式
mControlMode = array.getInt(R.styleable.DownloadProgressView_dpv_control_mode, MODE_NORMAL);
array.recycle();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
//計算出圓角半徑
mRadius = Math.min(mViewWidth, mViewHeight) / 2f;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//裁剪圓角
clipRound(canvas);
//畫背景
drawBg(canvas);
//畫進度條
drawProgress(canvas);
//畫文字圖層
drawText(canvas);
}
//------------ getFrameXxx()方法都是處理padding ------------
private float getFrameLeft() {
return getPaddingStart();
}
private float getFrameRight() {
return mViewWidth - getPaddingEnd();
}
private float getFrameTop() {
return getPaddingTop();
}
private float getFrameBottom() {
return mViewHeight - getPaddingBottom();
}
//------------ getFrameXxx()方法都是處理padding ------------
/**
* 裁剪圓角
*/
private void clipRound(Canvas canvas) {
Path path = new Path();
RectF roundRect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight(), getFrameBottom());
path.addRoundRect(roundRect, mRadius, mRadius, Path.Direction.CW);
canvas.clipPath(path);
}
/**
* 畫背景
*/
private void drawBg(Canvas canvas) {
canvas.drawRect(new RectF(getFrameLeft(), getPaddingTop(), getFrameRight(), getFrameBottom()), mBgPaint);
}
/**
* 畫進度
*/
private void drawProgress(Canvas canvas) {
RectF rect = new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom());
canvas.drawRect(rect, mProgressPaint);
}
/**
* 畫文字
*/
private void drawText(Canvas canvas) {
mTextPaint.setColor(mPercentageTextColor);
//創(chuàng)建文字圖層
Bitmap textBitmap = Bitmap.createBitmap(mViewWidth, mViewHeight, Bitmap.Config.ARGB_8888);
Canvas textCanvas = new Canvas(textBitmap);
String textContent = mProgress + "%";
//計算文字Y軸坐標
float textY = mViewHeight / 2.0f - (mTextPaint.getFontMetricsInt().descent / 2.0f + mTextPaint.getFontMetricsInt().ascent / 2.0f);
textCanvas.drawText(textContent, mViewWidth / 2.0f, textY, mTextPaint);
//畫最上層的白色圖層,未相交時不會顯示出來
mTextPaint.setColor(mPercentageTextColor2);
mTextPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
textCanvas.drawRect(new RectF(getFrameLeft(), getFrameTop(), getFrameRight() * getProgressRatio(), getFrameBottom()), mTextPaint);
//畫結合后的圖層
canvas.drawBitmap(textBitmap, getFrameLeft(), getFrameTop(), mTextPaint);
mTextPaint.setXfermode(null);
textBitmap.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(handleMeasure(widthMeasureSpec, true), handleMeasure(heightMeasureSpec, false));
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
//攔截事件,然后讓父類不進行攔截
if (mControlMode == MODE_TOUCH && action == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
return true;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//拽托模式下才起效果
if (mControlMode == MODE_TOUCH) {
int action = event.getAction();
//包裹Down事件時的x坐標
if (action == MotionEvent.ACTION_DOWN) {
mTouchDownX = event.getX();
return true;
} else if (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_UP) {
//Move或Up的時候,計算拽托進度
float endX = event.getX();
//計算公式:百分比值 = 移動距離 / 總長度
float distanceX = Math.abs(endX - mTouchDownX);
float ratio = (distanceX * 1.0f) / (getFrameRight() - getFrameLeft());
//計算百分比應該有的進度:進度 = 總進度 * 進度百分比值
float progress = mMaxProgress * ratio;
setProgress((int) progress);
return true;
}
return super.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
/**
* 處理MeasureSpec
*/
private int handleMeasure(int measureSpec, boolean isWidth) {
int result;
if (isWidth) {
result = mDefaultMinWidth;
} else {
result = mDefaultMinHeight;
}
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
//處理wrap_content的情況
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* 設置進度最大值
*/
public DownloadProgressView setMaxProgress(int maxProgress) {
mMaxProgress = maxProgress;
invalidate();
return this;
}
/**
* 設置進度
*/
public void setProgress(int progress) {
if (progress >= 0 && progress <= 100) {
mProgress = progress;
invalidate();
if (mOnProgressUpdateListener != null) {
mOnProgressUpdateListener.onProgressUpdate(progress);
}
}
}
/**
* 獲取當前進度
*/
public int getProgress() {
return mProgress;
}
/**
* 獲取最大進度
*/
public int getMaxProgress() {
return mMaxProgress;
}
public interface OnProgressUpdateListener {
/**
* 進度更新時回調
*
* @param progress 當前進度
*/
void onProgressUpdate(int progress);
}
public void setOnProgressUpdateListener(OnProgressUpdateListener onProgressUpdateListener) {
mOnProgressUpdateListener = onProgressUpdateListener;
}
/**
* 獲取當前進度值比值
*/
private float getProgressRatio() {
return (mProgress / (mMaxProgress * 1.0f));
}
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
具體使用
在布局中添加控件
<com.zh.cavas.sample.widget.DownloadProgressView
android:id="@+id/download_progress"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
app:dpv_bg="#E6EAFB"
app:dpv_max_progress="100"
app:dpv_percentage_text_color2="@color/white"
app:dpv_percentage_text_size="14sp"
app:dpv_progress="0"
app:dpv_progress_bg="#3548FE"
tools:dpv_progress="50" />
Java代碼
private DownloadProgressView vDownloadProgressView;
@Override
protected void onCreate(Bundle savedInstanceState) {
vDownloadProgressView = view.findViewById(R.id.download_progress);
//設置進度監(jiān)聽
vDownloadProgressView.setOnProgressUpdateListener(new DownloadProgressView.OnProgressUpdateListener() {
@Override
public void onProgressUpdate(int progress) {
vProgressIndicator.setText("當前進度:" + progress);
}
});
//手動設置當前進度
vDownloadProgressView.setProgress(0);
//設置最大值
vDownloadProgressView.setMaxProgress(100);
}
}
到這里就結束啦。
以上就是Android實現(xiàn)下載進度條效果的詳細內容,更多關于Android 下載進度條的資料請關注腳本之家其它相關文章!
相關文章
Android編程開發(fā)之EditText實現(xiàn)輸入QQ表情圖像的方法
這篇文章主要介紹了Android編程開發(fā)之EditText實現(xiàn)輸入QQ表情圖像的方法,涉及Android多媒體文件及EditText的相關操作技巧,需要的朋友可以參考下2015-12-12
詳解Android應用中preference首選項的編寫方法
這篇文章主要介紹了Android應用中preference首選項的編寫方法,或許Apple將其翻譯為'偏好設置'更直觀些,即用戶對應用的一些個性化調整菜單,需要的朋友可以參考下2016-04-04
Android開發(fā)教程之ContentProvider數(shù)據(jù)存儲
這篇文章主要介紹了Android開發(fā)教程之ContentProvider數(shù)據(jù)存儲的相關資料,需要的朋友可以參考下2016-12-12
Android Tablayout 自定義Tab布局的使用案例
這篇文章主要介紹了Android Tablayout 自定義Tab布局的使用案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Android Cocos Creator游戲開發(fā)平臺打包優(yōu)化實現(xiàn)方案
Cocos Creator是一款輕量、高效、免費開源的跨平臺游戲引擎,同時也是實時3D內容創(chuàng)作平臺,不僅支持2D、3D的游戲開發(fā),同時在HMI、IoT、XR、虛擬人偶等領域,均可提供一套完善的行業(yè)解決方案2022-11-11

