編輯:關於 Android 程式設計

這個進度條有兩個視覺重點:進度末端的水滴形滑塊,以及進度條本身由綠到藍的漸變填色。下面直接上程式碼並拆解關鍵。
package com.susan.project.myapplication;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
/**
* 漸變 進度條
*/
public class ProgressSeek extends View {
/** 進度條的寬度 */
private int view_width;
/** 畫布的寬度 */
private int view_base_width;
/** 控件的寬度 */
private int view_edge_width;
/** 進度 */
private int progress;
private Canvas cacheCanvas;
/** 背景顏色的畫筆 */
private Paint backgroundPaint;
/** 進度條的畫筆 */
private Paint progressPaint;
/** 進度末端的圖 */
private Bitmap bitmap;
private int bitmapWidth;
private int bitmapHeight;
private Context context;
// 漸變色開始
private static final int DEFAULT_START_COLOR = Color.parseColor("#34DAB5");
// 漸變色結束
private static final int DEFAULT_END_COLOR = Color.parseColor("#27A5FE");
/** 緩存圖片 */
private Bitmap cacheBitmap;
public ProgressSeek(Context context) {
super(context);
initView(context);
}
public ProgressSeek(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public ProgressSeek(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
this.context = context;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.thumb);
bitmapWidth = bitmap.getWidth();
bitmapHeight = bitmap.getHeight();
backgroundPaint = new Paint();
backgroundPaint.setStrokeWidth(bitmapWidth);
backgroundPaint.setColor(Color.parseColor("#cccccc"));
backgroundPaint.setDither(true);
backgroundPaint.setAntiAlias(true);
progressPaint = new Paint();
progressPaint.setStrokeWidth(bitmapWidth);
progressPaint.setDither(true);
progressPaint.setAntiAlias(true);
DisplayMetrics d = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(d);
view_base_width = d.widthPixels;
}
public void init(int progress) {
this.progress = progress;
if (view_width == 0) {
// 第一次進來,以螢幕寬度為基準計算
view_width = view_base_width * progress / 100;
} else {
view_width = view_edge_width * progress / 100;
}
if (cacheBitmap != null) {
if (!cacheBitmap.isRecycled()) {
cacheBitmap.recycle();
cacheBitmap = null;
}
cacheCanvas = null;
}
cacheBitmap = Bitmap.createBitmap(view_base_width, bitmapHeight * 2, Bitmap.Config.ARGB_8888);
if (cacheCanvas == null) {
cacheCanvas = new Canvas();
cacheCanvas.setBitmap(cacheBitmap);
}
// 畫背景
RectF r = new RectF();
r.left = 0;
r.top = bitmapHeight;
r.right = view_base_width;
r.bottom = bitmapWidth + 10;
cacheCanvas.drawRoundRect(r, 5f, 5f, backgroundPaint);
if (progress > 0) {
// 設置漸變
LinearGradient lg = new LinearGradient(0, 0, view_width, bitmapWidth,
DEFAULT_START_COLOR, DEFAULT_END_COLOR, Shader.TileMode.CLAMP);
progressPaint.setShader(lg);
RectF r1 = new RectF();
r.left = 0;
r.top = bitmapHeight;
r.right = view_width;
r.bottom = bitmapWidth + 10;
cacheCanvas.drawRoundRect(r, 5f, 5f, progressPaint);
cacheCanvas.drawBitmap(bitmap, view_width - bitmapWidth + 8, bitmapHeight / 2 + 6, new Paint());
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint bmpPaint = new Paint();
// 將 cacheBitmap 繪制到該 View 組件
if (cacheBitmap != null) {
canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);
}
view_edge_width = this.getWidth();
Log.e("打出來看看控件的寬度:", view_edge_width + "");
init(progress);
}
}
核心只有一個類別:LinearGradient。它是 Shader 的一種,建構參數是 (x0, y0, x1, y1, color0, color1, tileMode)——前四個數字定義漸變的方向與範圍,這裡從 (0, 0) 到 (view_width, bitmapWidth),也就是水平方向;後面兩個是起訖顏色。
關鍵的一步是 progressPaint.setShader(lg)。設定 Shader 之後,畫筆不再是單一純色,drawRoundRect() 填出的形狀就會沿著 Shader 定義的方向呈現漸變。這比「準備一堆不同顏色的圖片再拼接」要優雅得多,也更容易調整。
Shader.TileMode.CLAMP 的意義是:超出漸變範圍的區域,邊緣顏色會向外延伸填滿。若改用 REPEAT 則會重複循環,MIRROR 則是鏡像來回。這裡選 CLAMP 是因為漸變範圍已對齊進度寬度,不需要額外的填充分工。
水滴圖案並不是用 Canvas 畫出來的,而是一張 mipmap/thumb 的 PNG 素材,透過 drawBitmap() 貼到進度條末端:
cacheCanvas.drawBitmap(bitmap, view_width - bitmapWidth + 8, bitmapHeight / 2 + 6, new Paint());
橫向座標 view_width - bitmapWidth + 8 讓水滴中心對齊進度末端;那個 + 8 是為了修正素材本身的透明邊距。縱向 bitmapHeight / 2 + 6 讓水滴垂直居中於進度條上。這兩個數字是反覆對著畫面調出來的,換素材時必須重新微調。
另外注意 backgroundPaint.setStrokeWidth(bitmapWidth)——把筆觸粗細設成水滴的寬度,讓圓角矩形的高度與水滴視覺上等寬,兩者才不會一個胖一個瘦。
程式碼裡有個 cacheBitmap 與 cacheCanvas。做法是先在一張離屏 Bitmap 上把所有內容畫好,再在 onDraw() 中一次 drawBitmap() 貼上去。
這是自定義 View 的常見優化手法。直接在 onDraw() 裡呼叫多次 drawRoundRect()、setShader()、drawBitmap(),每次重繪都要重跑一遍;改成先繪製到快取 Bitmap,onDraw() 就只剩一次貼圖,能明顯降低重繪成本。特別是 LinearGradient 的建立與 Shader 的設定開銷不低,適合這樣處理。
佈局檔直接引用全限定類別名稱:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.susan.project.myapplication.ProgressSeek
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="80dp">
</com.susan.project.myapplication.ProgressSeek>
<com.susan.project.myapplication.ProgressSeek
android:id="@+id/progress1"
android:layout_width="match_parent"
android:layout_height="80dp">
</com.susan.project.myapplication.ProgressSeek>
<com.susan.project.myapplication.ProgressSeek
android:id="@+id/progress2"
android:layout_width="match_parent"
android:layout_height="80dp">
</com.susan.project.myapplication.ProgressSeek>
<com.susan.project.myapplication.ProgressSeek
android:id="@+id/progress3"
android:layout_width="match_parent"
android:layout_height="80dp">
</com.susan.project.myapplication.ProgressSeek>
</LinearLayout>
Activity 中設定不同進度:
package com.susan.project.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
private ProgressSeek progress;
private ProgressSeek progress1;
private ProgressSeek progress2;
private ProgressSeek progress3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressSeek) findViewById(R.id.progress);
progress.init(0);
progress1 = (ProgressSeek) findViewById(R.id.progress1);
progress1.init(2);
progress2 = (ProgressSeek) findViewById(R.id.progress2);
progress2.init(50);
progress3 = (ProgressSeek) findViewById(R.id.progress3);
progress3.init(100);
}
}
範例能跑,效果也對,但若要放進正式專案,有幾處值得調整。
onDraw 中的副作用要拿掉。onDraw() 裡呼叫 init(progress),而 init() 內部又有 invalidate(),形成「繪製 → 觸發重繪 → 再繪製」的迴圈。目前靠 Bitmap 快取勉強撐住,但這是很脆弱的寫法。比較正規的做法是把快取 Bitmap 的建立搬到 onSizeChanged() 或 onMeasure(),讓 onDraw() 保持純繪製。
進度變化時應該 recycling 舊 Bitmap。目前的 init() 每次都會 recycle 舊的再建新的,若呼叫頻繁會造成記憶體抖動。實務上可以只在尺寸變化時重建 Bitmap,進度變化時僅重畫內容。
把寫死的數字抽成自定義屬性。漸變起訖色、圓角半徑、水滴偏移量目前都寫在程式碼裡。用 declare-styleable 抽出來,同一個控制項才能在不同頁面呈現不同風格,也不必為了改個顏色去動邏輯。
水滴位置應綁定實際進度而非每次重算。另外,((Activity) context) 的強制轉型限制了這個 View 只能在 Activity 中使用,放進 Fragment 或 Dialog 就會轉型失敗。改用 context.getSystemService(WINDOW_SERVICE) 取得螢幕尺寸會更通用。
以上就是這個水滴漸變進度條的完整實作。核心觀念其實就三個:LinearGradient 做漸變、setShader() 把漸變套到畫筆上、雙緩存降低重繪成本。掌握這三點,其他類似的自定義進度元件都能快速改出來。
微信電腦版誤發訊息怎麼辦?撤回功能操作教學
微信電腦版可撤回誤發訊息。在聊天視窗中找到訊息,按右鍵選擇撤回,對話中會顯示已撤回提示。 此功能可減少打錯字或傳錯檔案的困擾。
Android 7.0 MessageQueue 深層解析:Java 與 Native 雙層訊息機制
為什麼 MessageQueue 不只是 Java 層的資料 Android 的訊息處理機制常由 Handler、Looper 與 MessageQueue 組成。表面上
ZXing 3.0 二維碼掃描與生成的最小化接入筆記
官方專案網址:https://github.com/zxing/zxing/tree/zxing-3.0.0 core 套件下載:https://repo1.maven.
Android 4.0 USB Camera 实战(四):接入 CMOS 图像传感器
上一篇讲了 UVC 标准的处理流程,这一篇顺手把 CMOS 也接进来。两者在操作上基本一致,HAL 层其实已经预留了 CMOS 的接口(Java_com_dao_usbc