編輯:關於 Android 開發
聲明:本文原始碼出自「實現雪花飛舞效果」一文(有改動),我主要借這個例子來把自訂 View 的實作流程講清楚。
自訂 View 大致可以分成三類:
第一類最能幫助你理解「測量—配置—繪製」這條主線,所以特別值得走一遍。
public class SnowView extends View {
Random random;
private static final int NUM_SNOWFLAKES = 15; // 雪花數量
private static final int DELAY = 1; // 畫面延時刷新時間
private SnowFlake[] snowflakes; // 雪花物件陣列
public SnowView(Context context) { super(context); }
public SnowView(Context context, AttributeSet attrs) { super(context, attrs); }
public SnowView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected void resize(int width, int height) {
random = new Random();
snowflakes = new SnowFlake[NUM_SNOWFLAKES];
for (int i = 0; i < NUM_SNOWFLAKES; i++) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.rgb(random.getColor(), random.getColor(), random.getColor()));
snowflakes[i] = SnowFlake.create(width, height, paint);
}
}
/** View 中的呼叫順序:onSizeChanged() > onDraw() */
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw || h != oldh) {
resize(w, h);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (SnowFlake snowFlake : snowflakes) {
snowFlake.draw(canvas);
}
// 透過 Handler 在主執行緒定時重繪
getHandler().postDelayed(runnable, DELAY);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
invalidate(); // 會清掉原畫面並重新觸發 onDraw
}
};
}
onSizeChanged() 一定早於 onDraw() 執行。當 View 尺寸改變時由系統呼叫,在這個例子裡我們用它判斷尺寸是否變動,若有變動就呼叫 resize() 並把寬高傳進去。resize() 裡建立雪花物件陣列,用迴圈產生指定數量的雪花,每片雪花各自持有自己的 Paint(顏色、粗細、抗鋸齒、空心或實心等屬性都在這裡決定),再呼叫 SnowFlake 的 create() 設定尺寸與初始位置,最後把這些參數以物件形式存進陣列,等 onDraw() 來取用。
一句話記法:Canvas 決定畫什麼,Paint 決定用什麼樣的筆觸畫。
onDraw() 則用迴圈依序把陣列裡每一片雪花畫出來,接著用 Handler 定時重繪,動畫就出來了。
public class SnowFlake {
private static final float ANGE_RANGE = 0.1f;
private static final float HALF_ANGLE_RANGE = ANGE_RANGE / 2f;
private static final float HALF_PI = (float) Math.PI / 2f;
private static final float ANGLE_SEED = 25f;
private static final float ANGLE_DIVISOR = 10000f;
private static final float INCREMENT_LOWER = 2f;
private static final float INCREMENT_UPPER = 4f;
private static final float FLAKE_SIZE_LOWER = 7f; // 最小雪花
private static final float FLAKE_SIZE_UPPER = 20f; // 最大雪花
private final Random random;
private final Point position;
private float angle;
private final float increment;
private final float flakeSize;
private final Paint paint;
public static SnowFlake create(int width, int height, Paint paint) {
Random random = new Random();
int x = random.getRandom(width);
int y = random.getRandom(height);
Point position = new Point(x, y);
// 初始角度落在 [HALF_PI - 0.05, HALF_PI + 0.05)
float angle = random.getRandom(ANGLE_SEED) / ANGLE_SEED * ANGE_RANGE
+ HALF_PI - HALF_ANGLE_RANGE;
float increment = random.getRandom(INCREMENT_LOWER, INCREMENT_UPPER); // [2f, 4f)
float flakeSize = random.getRandom(FLAKE_SIZE_LOWER, FLAKE_SIZE_UPPER); // [7f, 20f)
return new SnowFlake(random, position, angle, increment, flakeSize, paint);
}
SnowFlake(Random random, Point position, float angle,
float increment, float flakeSize, Paint paint) {
this.random = random;
this.position = position;
this.angle = angle;
this.increment = increment;
this.flakeSize = flakeSize;
this.paint = paint;
}
private void move(int width, int height) {
// x 方向位移小、y 方向位移大,讓雪花快點落下
double x = position.x + (increment * Math.cos(angle));
double y = position.y + (increment * Math.sin(angle));
// 每次移動都對角度做一點隨機擾動,模擬飄搖感
angle += random.getRandom(-ANGLE_SEED, ANGLE_SEED) / ANGLE_DIVISOR;
position.set((int) x, (int) y);
if (!isInside(width, height)) {
reset(width); // 飄出畫面就從頂端重新開始
}
}
private boolean isInside(int width, int height) {
int x = position.x;
int y = position.y;
return x >= -flakeSize - 1 && x + flakeSize <= width
&& y >= -flakeSize - 1 && y - flakeSize < height;
}
private void reset(int width) {
// View 的原點在左上角,y 為負值就代表在畫面上方
position.x = random.getRandom(width);
position.y = (int) (-flakeSize - 1);
angle = random.getRandom(ANGLE_SEED) / ANGLE_SEED * ANGE_RANGE
+ HALF_PI - HALF_ANGLE_RANGE;
}
public void draw(Canvas canvas) {
int width = canvas.getWidth();
int height = canvas.getHeight();
move(width, height);
canvas.drawCircle(position.x, position.y, flakeSize, paint);
}
}
值得注意的一點:angle 被限制在 π/2 附近的小區間,所以 cos(angle) ≈ 1 而 sin(angle) 接近 0,x 方向幾乎等速前進、y 方向位移很小——但 y 每幀都在累加,加上每幀的隨機擾動,看起來就是雪花緩緩飄落又輕輕搖晃的感覺。
public class Random {
private static final java.util.Random RANDOM = new java.util.Random();
public float getRandom(float lower, float upper) {
float min = Math.min(lower, upper);
float max = Math.max(lower, upper);
return getRandom(max - min) + min;
}
public float getRandom(float upper) {
return RANDOM.nextFloat() * upper; // [0, upper)
}
public int getRandom(int upper) {
return RANDOM.nextInt(upper); // [0, upper)
}
public int getColor() {
return RANDOM.nextInt(255);
}
}
自訂 View 在 XML 中要寫完整的類別路徑,並把它疊在背景圖上層:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:src="@drawable/tree" />
<com.example.jwwsnow.SnowView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignBottom="@id/image"
android:layout_alignEnd="@id/image"
android:layout_alignLeft="@id/image"
android:layout_alignRight="@id/image"
android:layout_alignStart="@id/image"
android:layout_alignTop="@id/image" />
</RelativeLayout>
整篇看下來,自訂 View 的骨架其實就是三件事:onSizeChanged 準備資料、onDraw 負責繪製、invalidate 驅動動畫。把這條主線掌握住,之後要做任何自繪動畫都有依循的模板。建議搭配原始文章一起看,收穫會更完整。
ELF Format 筆記(十五):符號哈希表與查詢流程
符號哈希表存在的理由 作者:ilocker(關注 Android 安全)。 符號哈希表(symbol hash table)並不是 ELF 規範的一部分,而是為了加速符號
Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入
Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入 這篇記錄如何寫一個簡單的網路圖片查看器:使用者在輸入框貼上圖片網址
Android 自定義對話框:打造美觀_unique的彈窗
擺脫系統預設樣式,做一個有質感的彈窗 Android 自帶的對話框雖然能用,但樣式單調。為了更美觀,很多開發者會自定義對話框的佈局。下圖為點擊「彈出自定義對話框」按鈕後的
Android Studio 下 NDK 开发(一):从配置环境到 JNI 调用
Android Studio 下 NDK 开发(一):从配置环境到 JNI 调用 捣鼓了一天的 NDK,总结一下。在 Eclipse 下开发 NDK 似乎挺麻烦,书上的做