Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義控件實戰:仿安全衛士的圓形圓點進度條(一鍵加速)

編輯:Android 省電與效能提升

一、源代碼

源代碼及 demo 可下載(此進度條為開源項目,後續會持續添加與更新)。

二、緣起

某天在開發交流群裡,有位同學想實現這麼一個進度條,卻發現網上找不到現成的開源項目。

看到這張圖是不是特別眼熟?簡直讓人忍不住想點一下。我覺得挺有意思,正好也有一段時間沒寫自定義控件了,索性復習復習(老實說,擱久了思路還在,卻不知從何下手)。花了差不多一整天,終於把它搞定了。先看效果圖:

三種顯示模式:

模擬進度動畫效果:

它的特點:

· 提供三種可選的顯示模式;
· 始終完整顯示在控件範圍內,寬高不一致時以較短邊為準;
· 所有顏色均可自定義;
· 百分比、單位、按鈕的字號都可自定義;
· 單位與按鈕的文字內容可自定義;
· 單位與百分比的對齊方式可選(見下文「繪製單位」);
· 按鈕與百分比的垂直間距可調;
· 按鈕支持設置點擊事件;
· 可在子線程中直接更新進度。

三、設計剖析

看到這張圖,可以判斷它由四部分組成:

· 最外層的圓點
· 百分比
· 單位
· 按鈕

動手前先明確自定義控件的通用步驟:

· 分析控件各部分的屬性,在 res/values/attrs.xml 中定義;
· 實現三個基本構造方法,並在其中獲取屬性值或默認值;
· 重寫 onDraw(Canvas canvas) 繪製界面;
·(可選)處理觸摸事件;
· 在布局文件中使用,別忘了在根布局添加命名空間(如 xmlns:zjun="https://schemas.android.com/apk/res-auto")。

下面逐個拆解。

1、繪製最外層的圓點

最外層的圓點乍看很多,一圈下來感覺有上百個。當前百分比是 65,數了一下確實是 65 個白點,剩下的灰點自然就是 35 個。這樣一圈點的總數就確定為 100 個。

點與點之間的間距看上去恰好是一個點的空間,一圈就是 200 個連續圓點,且圓點內切於控件邊界。

它們的關係是:R0 = R1 + r;…… ①
其中 R0 為控件尺寸(min(getWidth(), getHeight()))的一半,R1 是圓點圓心所在軌跡圓的半徑,r 為圓點半徑。

另外,這 200 個連續圓點分佈在以 R1 為半徑的圓上,彼此外切,因此每個圓點佔據 360°/200 = 1.8°。

關係式:sin(0.9°) = r / R1 …… ②

聯立 ① 和 ②,可得 r 與 R0 的關係。實際試出來圓點間距偏大,於是把 sin(0.9°) 提到 sin(1°),這樣就飽滿多了。

 mSin_1 = (float) Math.sin(Math.toRadians(1)); // 計算圓點半徑 float outerRadius = (getWidth() < getHeight() ? getWidth() : getHeight()) / 2f; float dotRadius = mSin_1 * outerRadius / (1 + mSin_1);

半徑求出來後,圓心位置也確定了。畫圓點時一圈共 100 個,可以用 canvas 的旋轉來繪製,每畫一個就旋轉 3.6°(360°/100)。

至於進度,可以先畫已完成部分再畫未完成部分,也可以反過來。這裡我選前者,一方面避免重複繪製,另一方面防止已完成顏色帶透明度時,疊加後變色。

 float centerX = getWidth() / 2f; float centerY = getHeight() / 2f; // 1 畫進度 mPaint.setColor(dotColor); mPaint.setStyle(Paint.Style.FILL); int count = 0; // 1.1 當前進度 while (count++ < percent) { canvas.drawCircle(centerX, centerY - outerRadius + dotRadius, dotRadius, mPaint); canvas.rotate(3.6f, centerX, centerY); } // 1.2 未完成進度 mPaint.setColor(dotBgColor); count--; while (count++ < 100) { canvas.drawCircle(centerX, centerY - outerRadius + dotRadius, dotRadius, mPaint); canvas.rotate(3.6f, centerX, centerY); }

2、繪製百分比

百分比本質就是文字,直接用 canvas.drawText() 繪製即可。

 mPaint.setTextSize(percentTextSize); mPaint.setColor(percentTextColor); canvas.drawText(percent + "", centerX - textWidth / 2, baseline, mPaint);

關鍵是找好起始位置,並注意水平與垂直兩個方向的對齊。

2.1 水平對齊

先測量文字寬度,左側起始位置即 centerX - textWidth/2。這裡的 textWidth 需要把單位字體的寬度也算進去。

 mPaint.setTextSize(percentTextSize); float percentTextWidth = mPaint.measureText(percent + "");

2.3 垂直對齊

baseline 是 y 方向的起始位置,最初我設為 centerY + percentTextSize/2,結果默認模式下就成了這樣:

這哪是垂直居中,簡直像被萬有引力拽下去了。後來找到原因:y 坐標指的是 baseline,而不是我們直覺以為的 bottom。看下面這張圖(ascent 數值與參考博客略有出入,但這張圖是通過自定義控件直接繪製出來的,準確性毋庸置疑):

說明:

· top、bottom、ascent、descent 都可直接從 FontMetrics 獲取,且都以 baseline 為基準;
· baseline 就是 canvas.drawText(text, x, y, paint) 中的 y;
· center 是 ascent 與 descent 的中線,即 (ascent + descent)/2,也就是文字的中線。

FontMetrics 在設置字號後即可獲取:

 mPaint.setTextSize(textHeight); Paint.FontMetrics fm = mPaint.getFontMetrics();

所以要真正居中,baseline 更準確的算法是:

 baseline = centerY + (fm.descent - fm.ascent)/2 - fm.descent;

可以這樣理解:當文字居中時,中線的 y 坐標就是 centerY,加上 (fm.descent - fm.ascent)/2 到達 descent 線,再減去 fm.descent 就到達 baseline 線。

修正後的效果:

另一個同樣準確的寫法:

 baseline = centerY + (fm.bottom- fm.top)/2 - fm.bottom;

3、繪製單位

繪製方式與百分比相同,只是起始 x 坐標緊接百分比之後。

但如果單位不是「%」而是「分」之類的中文,就無法與百分比數字在底部對齊了。強迫症驅使下,我又給自己出了道難題。

回看前面 baseline 的推敲,不難發現字母、數字、漢字的底部對齊方式並不一樣(圖中那些文字正是為此準備的)。於是新增了一個特殊屬性 unitTextAlignMode,用來控制單位與百分比的對齊方式,共三種:

· DEFAULT:只要底部能與 baseline 對齊的字符都適用,如 %、a、b……
· CN:中文用它
· EN:針對帶尾巴的英文字母和符號,如 g、j、p、q、y、[、]、{、}、|……

原理是根據字號做微調:

 switch (unitTextAlignMode) { case UNIT_TEXT_ALIGN_MODE_CN: baseline -= fm_unit.descent / 4; break; case UNIT_TEXT_ALIGN_MODE_EN: baseline -= fm_unit.descent * 2/3; }

效果如何?不急,這裡正好有展品,看完再選:

百分比與單位字號相同:

百分比字號大於單位字號:

4、繪製按鈕

主要是背景。仔細看可以這樣拆:中間一個長方形,兩端各一個半圓。長方形長度等於文字寬度,高度為字高的兩倍。

繪製時可借助 Path 一次畫完:

 mPath.reset(); mPath.moveTo(mButtonRect_start.x, mButtonRect_start.y); mPath.rLineTo(buttonTextWidth, 0); float left = centerX + buttonTextWidth/2 - mButtonRadius; float top = centerY + buttonTopOffset; float right = left + 2 * mButtonRadius; float bottom = top + 2 * mButtonRadius; mRectF.set(left, top, right, bottom); mPath.arcTo(mRectF, 270, 180); // 參數1:內切這個方形,參數2:開始角度,參數3:畫的角度范圍 mPath.rLineTo(-buttonTextWidth, 0); mRectF.offset(-buttonTextWidth, 0); // 平移位置 mPath.arcTo(mRectF, 90, 180); mPath.close(); canvas.drawPath(mPath, mPaint);

5、處理按鈕的點擊事件

要處理按鈕點擊,先得判斷觸摸點是否落在按鈕內。與繪製思路一致,分別判斷是否在矩形、左半圓、右半圓中。

矩形好判斷;左右半圓則借助解析幾何:判斷點 (x, y) 是否在圓 (x0, y0, r) 內,先將點坐標減去圓心坐標,把原點平移到圓心,若在圓內必然滿足:

(x−x0)² + (y−y0)² ≤ r²

代碼實現如下:

 /** * 判斷坐標是否在按鈕中 * @param x 坐標的x * @param y 坐標的y * @return true-在按鈕中,false-不在按鈕中 */ private boolean isTouchInButton(final float x, final float y) { // 判斷是否在按鈕矩形中 if (x >= mButtonRect_start.x && x <= mButtonRect_end.x && y >= mButtonRect_start.y && y <= mButtonRect_end.y) { return true; } // 判斷是否在左邊半圓中:另一半圓在矩形中,也屬於按鈕范圍,所以直接判斷整個圓即可 // 把坐標系移到圓心再判斷 float centerX = mButtonRect_start.x; float centerY = (mButtonRect_start.y + mButtonRect_end.y) / 2; float newX = x - centerX; float newY = y - centerY; if (newX * newX + newY * newY <= mButtonRadius * mButtonRadius) { return true; } // 判斷是否在右邊半圓中 centerX = mButtonRect_end.x; newX = x - centerX; return newX * newX + newY * newY <= mButtonRadius * mButtonRadius; }

按鈕事件在 onTouchEvent() 中攔截,這樣才能區分「點擊按鈕」和「點擊控件其他區域」:

 @Override public boolean onTouchEvent(MotionEvent event) { if (showMode == SHOW_MODE_ALL) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (isTouchInButton(event.getX(), event.getY())) { mIsButtonTouched = true; postInvalidate(); } break; case MotionEvent.ACTION_MOVE: if (mIsButtonTouched) { if (!isTouchInButton(event.getX(), event.getY())) { mIsButtonTouched = false; postInvalidate(); } } break; case MotionEvent.ACTION_UP: if (mIsButtonTouched && mButtonClickListener != null) { mButtonClickListener.onClick(this); } mIsButtonTouched = false; postInvalidate(); } if (mIsButtonTouched) { return true; } } return super.onTouchEvent(event); }

四、核心代碼

除了上面的按鈕事件處理,還有兩個主要方法:構造方法中獲取屬性值或默認值,以及 onDraw() 中的繪製邏輯。

 public CircleDotProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CircleDotProgressBar); // 獲取自定義屬性值或默認值 progressMax = ta.getInteger(R.styleable.CircleDotProgressBar_progressMax, 100); dotColor = ta.getColor(R.styleable.CircleDotProgressBar_dotColor, Color.WHITE); dotBgColor = ta.getColor(R.styleable.CircleDotProgressBar_dotBgColor, Color.GRAY); showMode = ta.getInt(R.styleable.CircleDotProgressBar_showMode, SHOW_MODE_PERCENT); if (showMode != SHOW_MODE_NULL) { percentTextSize = ta.getDimension(R.styleable.CircleDotProgressBar_percentTextSize, dp2px(30)); percentTextColor = ta.getInt(R.styleable.CircleDotProgressBar_percentTextColor, Color.WHITE); unitText = ta.getString(R.styleable.CircleDotProgressBar_unitText); unitTextSize = ta.getDimension(R.styleable.CircleDotProgressBar_unitTextSize, percentTextSize); unitTextColor = ta.getInt(R.styleable.CircleDotProgressBar_unitTextColor, Color.WHITE); unitTextAlignMode = ta.getInt(R.styleable.CircleDotProgressBar_unitTextAlignMode, UNIT_TEXT_ALIGN_MODE_DEFAULT); if (unitText == null) { unitText = "%"; } } if (showMode == SHOW_MODE_ALL) { buttonText = ta.getString(R.styleable.CircleDotProgressBar_buttonText); buttonTextSize = ta.getDimension(R.styleable.CircleDotProgressBar_buttonTextSize, dp2px(15)); buttonTextColor = ta.getInt(R.styleable.CircleDotProgressBar_buttonTextColor, Color.GRAY); buttonBgColor = ta.getInt(R.styleable.CircleDotProgressBar_buttonBgColor, Color.WHITE); buttonClickColor = ta.getInt(R.styleable.CircleDotProgressBar_buttonClickColor, buttonBgColor); buttonClickBgColor = ta.getInt(R.styleable.CircleDotProgressBar_buttonClickBgColor, buttonTextColor); buttonTopOffset = ta.getDimension(R.styleable.CircleDotProgressBar_buttonTopOffset, dp2px(15)); if (buttonText == null) { buttonText = context.getString(R.string.CircleDotProgressBar_speed_up_one_key); } } ta.recycle(); // 其他准備工作 mSin_1 = (float) Math.sin(Math.toRadians(1)); // 求sin(1°)。角度需轉換成弧度 mPaint = new Paint(); mPaint.setAntiAlias(true); // 消除鋸齒 mPath = new Path(); mRectF = new RectF(); mButtonRect_start = new PointF(); mButtonRect_end = new PointF(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 計算圓點半徑 float outerRadius = (getWidth() < getHeight() ? getWidth() : getHeight()) / 2f; float centerX = getWidth() / 2f; float centerY = getHeight() / 2f; // outerRadius = innerRadius + dotRadius // sin((360°/200)/2) = sin(0.9°) = dotRadius / innerRadius; // 為了讓圓點飽滿一些,把角度0.9°增加0.1°到1° float dotRadius = mSin_1 * outerRadius / (1 + mSin_1); // 1 畫進度 mPaint.setColor(dotColor); mPaint.setStyle(Paint.Style.FILL); int count = 0; // 1.1 當前進度 while (count++ < percent) { canvas.drawCircle(centerX, centerY - outerRadius + dotRadius, dotRadius, mPaint); canvas.rotate(3.6f, centerX, centerY); } // 1.2 未完成進度 mPaint.setColor(dotBgColor); count--; while (count++ < 100) { canvas.drawCircle(centerX, centerY - outerRadius + dotRadius, dotRadius, mPaint); canvas.rotate(3.6f, centerX, centerY); } if (showMode == SHOW_MODE_NULL) { return; } if (showMode == SHOW_MODE_PERCENT) { // 2 畫百分比和單位:水平和垂直居中 mPaint.setTextSize(percentTextSize); float percentTextWidth = mPaint.measureText(percent + ""); mPaint.setTextSize(unitTextSize); float unitTextWidth = mPaint.measureText(unitText); Paint.FontMetrics fm_unit = mPaint.getFontMetrics(); float textWidth = percentTextWidth + unitTextWidth; float textHeight = percentTextSize > unitTextSize ? percentTextSize : unitTextSize; mPaint.setTextSize(textHeight); Paint.FontMetrics fm = mPaint.getFontMetrics(); float baseline = centerY + (fm.descent - fm.ascent)/2 - fm.descent; // 2.1 畫百分比 mPaint.setTextSize(percentTextSize); mPaint.setColor(percentTextColor); canvas.drawText(percent + "", centerX - textWidth / 2, baseline, mPaint); // 2.2 畫單位 mPaint.setTextSize(unitTextSize); mPaint.setColor(unitTextColor); switch (unitTextAlignMode) { case UNIT_TEXT_ALIGN_MODE_CN: baseline -= fm_unit.descent / 4; break; case UNIT_TEXT_ALIGN_MODE_EN: baseline -= fm_unit.descent * 2/3; } canvas.drawText(unitText, centerX - textWidth / 2 + percentTextWidth, baseline, mPaint); }else if (showMode == SHOW_MODE_ALL) { // 2 畫百分比和單位:水平居中 mPaint.setTextSize(percentTextSize); float percentTextWidth = mPaint.measureText(percent + ""); mPaint.setTextSize(unitTextSize); float unitTextWidth = mPaint.measureText(unitText); Paint.FontMetrics fm_unit = mPaint.getFontMetrics(); float textWidth = percentTextWidth + unitTextWidth; // 2.1 畫百分比 mPaint.setTextSize(percentTextSize); mPaint.setColor(percentTextColor); float baseline_per = centerY; canvas.drawText(percent + "", centerX - textWidth / 2, baseline_per, mPaint); // 2.2 畫單位 mPaint.setTextSize(unitTextSize); mPaint.setColor(unitTextColor); switch (unitTextAlignMode) { case UNIT_TEXT_ALIGN_MODE_CN: baseline_per -= fm_unit.descent / 4; break; case UNIT_TEXT_ALIGN_MODE_EN: baseline_per -= fm_unit.descent * 2/3; } canvas.drawText(unitText, centerX - textWidth / 2 + percentTextWidth, baseline_per, mPaint); // 3 畫按鈕 mPaint.setTextSize(buttonTextSize); float buttonTextWidth = mPaint.measureText(buttonText); Paint.FontMetrics fm = mPaint.getFontMetrics(); // 3.1 畫按鈕背景 mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mIsButtonTouched ? buttonClickBgColor : buttonBgColor); float buttonHeight = 2 * buttonTextSize; mButtonRadius = buttonHeight / 2; mButtonRect_start.set(centerX - buttonTextWidth / 2, centerY + buttonTopOffset); mButtonRect_end.set(centerX + buttonTextWidth/2, centerY + buttonTopOffset + buttonHeight); mPath.reset(); mPath.moveTo(mButtonRect_start.x, mButtonRect_start.y); mPath.rLineTo(buttonTextWidth, 0); float left = centerX + buttonTextWidth/2 - mButtonRadius; float top = centerY + buttonTopOffset; float right = left + 2 * mButtonRadius; float bottom = top + 2 * mButtonRadius; mRectF.set(left, top, right, bottom); mPath.arcTo(mRectF, 270, 180); mPath.rLineTo(-buttonTextWidth, 0); mRectF.offset(-buttonTextWidth, 0); mPath.arcTo(mRectF, 90, 180); mPath.close(); canvas.drawPath(mPath, mPaint); // 3.2 畫按鈕文本 mPaint.setColor(mIsButtonTouched ? buttonClickColor : buttonTextColor); float baseline = centerY + buttonTopOffset + buttonTextSize + (fm.descent - fm.ascent)/2 - fm.descent; canvas.drawText(buttonText, centerX - buttonTextWidth / 2, baseline, mPaint); } } /** * 設置進度 * 同步,允許多線程訪問 * @param progress 進度 */ public synchronized void setProgress(int progress) { if (progress < 0 || progress > progressMax) { throw new IllegalArgumentException(String.format("progress must between 0 and max(%d)", progressMax)); } this.progress = progress; percent = progress * 100 / progressMax; postInvalidate(); // 可以直接在子線程中調用,而invalidate()必須在主線程(UI線程)中調用 } public synchronized void setProgressMax(int progressMax) { if (progressMax < 0) { throw new IllegalArgumentException("progressMax mustn't smaller than 0"); } this.progressMax = progressMax; }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved