国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

Android實現(xiàn)下載進度條效果

瀏覽:7日期:2022-09-18 09:12:47
目錄最終效果和對比vivo商店效果分析1 - 計算進度分析2 - 繪制圓角矩形解決方案分析3 - 繪制文字和交匯手勢拓展完整代碼具體使用最終效果和對比vivo商店效果

vivo應(yīng)用商店下載效果:

Android實現(xiàn)下載進度條效果

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

Android實現(xiàn)下載進度條效果

分析1 - 計算進度

進度計算就比較簡單了,我們通過復(fù)寫onSizeChanged()方法,獲取到控件的寬后,先計算當前進度百分比,再將百分比乘以寬度,就可以得到應(yīng)該繪制的寬度了。

繪制圓角矩形需要傳一個Rect,Rect的構(gòu)造方法需要傳4個位置,分別是left、top、right、bottom,我們主要是計算不斷變化的right值。在drawProgress()方法中,right值為最大的寬度 * 進度百分比值。

/** * 控件寬 */private int mViewWidth;/** * 控件高 */private int mViewHeight;/** * 圓角弧度 */private float mRadius;/** * 當前進度 */private int mProgress;/** * 最大進度值 */private int mMaxProgress;@Overrideprotected 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%,計算出來的矩形長度比較小,會導(dǎo)致圓角不是滿的,缺陷效果見動圖(注意看剛從左側(cè)出來時圓角的大小)。

Android實現(xiàn)下載進度條效果

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設(shè)置了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黃色圓形為下層圖層。)

Android實現(xiàn)下載進度條效果

查閱文檔,我們發(fā)現(xiàn)SrcATop模式比較符合我們的需求,在SrcATop模式下,Src圖層不覆蓋Dst圖層的像素會被拋棄,只保留Src圖層覆蓋Dst圖層的圖層像素。

我們的思路是這樣的:畫4個圖層,最底部的灰色背景圖層,再上一層藍色進度圖層,接著是文字圖層,最上層是一層白色的進度圖層,重點在畫文字和白色進度圖層是添加了PorterDuffXfermode(SrcATop模式)。

白色進度和藍色進度的大小一直是同步的,但是因為PorterDuffXfermode的原因,白色圖層未覆蓋到文字時,一直都是被拋棄圖層像素,相當于是透明的,只有當和文字相交時,才會繪制出白色圖層,就顯示出了一半白色文字,一半藍色文字的效果,而其他部分都沒有和文字相交都被拋棄,都為透明。

繪制文字、白色進度圖層代碼,見drawText()方法。

@Overrideprotected 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); //畫結(jié)合后的圖層 canvas.drawBitmap(textBitmap, getFrameLeft(), getFrameTop(), mTextPaint); mTextPaint.setXfermode(null); textBitmap.recycle();}手勢拓展

經(jīng)過上面的進度、文字、交匯處理,進度條算是完整了,接下來拓展一下沒有的東西,例如手勢拖動,就像SeekBar一樣,當我們觸摸進度條時,進度會隨著移動而改變進度。

我們先重寫dispatchTouchEvent()方法,當down事件來到時,讓父控件不攔截,我們進行攔截。接著重寫onTouchEvent()方法,計算Move、Up時,移動的距離,計算出百分比和應(yīng)有的進度值,然后不斷調(diào)用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());//計算百分比應(yīng)該有的進度:進度 = 總進度 * 進度百分比值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);//畫結(jié)合后的圖層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());//計算百分比應(yīng)該有的進度:進度 = 總進度 * 進度百分比值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; } /** * 設(shè)置進度最大值 */ public DownloadProgressView setMaxProgress(int maxProgress) {mMaxProgress = maxProgress;invalidate();return this; } /** * 設(shè)置進度 */ 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 {/** * 進度更新時回調(diào) * * @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.DownloadProgressViewandroid: 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);//設(shè)置進度監(jiān)聽vDownloadProgressView.setOnProgressUpdateListener(new DownloadProgressView.OnProgressUpdateListener() { @Override public void onProgressUpdate(int progress) {vProgressIndicator.setText('當前進度:' + progress); }});//手動設(shè)置當前進度vDownloadProgressView.setProgress(0);//設(shè)置最大值vDownloadProgressView.setMaxProgress(100); }}

到這里就結(jié)束啦。

以上就是Android實現(xiàn)下載進度條效果的詳細內(nèi)容,更多關(guān)于Android 下載進度條的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標簽: Android
相關(guān)文章:
主站蜘蛛池模板: 欧美高清一区二区 | 国产a级一级久久毛片 | 美女被免费网站视频软件 | m男亚洲一区中文字幕 | 国产一级在线观看视频 | 99精品小视频| 欧美黑大粗硬毛片视频 | 老少配性xxxxxx | 国产亚洲视频在线播放大全 | 国内三级视频 | 九九精彩视频在线观看视频 | 成人一级片在线观看 | 女人被男人躁得好爽免费文 | 国产男女猛烈无遮档免费视频网站 | 国产va精品网站精品网站精品 | 成人自拍视频在线 | 亚洲欧美自拍一区 | 欧美日韩一区二区三 | 国产在线一区二区三区欧美 | 国产高清成人mv在线观看 | 在线成人毛片 | 成年男女拍拍拍免费视频 | 日本aaaa级 | 久久久不卡国产精品一区二区 | 欧美在线视频不卡 | 亚洲福利视频精选在线视频 | 久草免费手机视频 | 成人伊人 | 亚洲免费在线视频 | 欧美高清免费精品国产自 | 欧美一级毛片免费播放器 | 欧美日韩一区二区中文字幕视频 | 国产在线高清不卡免费播放 | 国产综合在线观看视频 | 456亚洲老头视频 | 日本香蕉一区二区三区 | 99热com| 久久影视一区 | 久草在线青青草 | 国产精品美女免费视频大全 | 亚洲一区二区三区免费观看 |