編輯:關於 Android 程式設計
在 Android 開發裡,Color 與 Drawable 幾乎無所不在。兩者有時候可以互相替換,有時候界線又涇渭分明。本文把 Drawable 的體系結構、各類子類與使用方式系統梳理一遍。
Drawable 是「可繪製物件」的通用抽象。和 View 不同,Drawable 身上沒有事件與互動方法,它只負責畫。我們通常為了實現複雜或炫麗的 UI 而自訂 View,其實自訂 Drawable 同樣能達到目的,而且往往更輕量。
Drawable 本身是抽象類,實務上我們用的是它的子類,全部住在 android.graphics.drawable 這個 package 下,例如 Bitmap、Layer、NinePatch、Scale、Shape、State 等等。
核心方法只有一個:draw(Canvas canvas)。Drawable 必須掛在某個 View 上才會被畫出來;畫多大由 setBounds() 決定;而真正觸發繪製的,是 View 自己的 draw 流程。
圓角圖片和圓形頭像這類需求,用自訂 Drawable 實現非常乾脆。先看效果:

圓角版本:
/**
* 圓角圖片
*/
public class RoundRectImageDrawable extends Drawable {
private RectF rectF;
private Paint mPaint;
private Bitmap bitmap;
public RoundRectImageDrawable(Bitmap bitmap) {
this.bitmap = bitmap;
// CLAMP 表示超出邊界時用邊緣像素填充;TileMode 另有 repeat、mirror
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
rectF = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
rectF = new RectF(left, top, right, bottom);
}
@Override
public void draw(Canvas canvas) {
// 60 即圓角半徑
canvas.drawRoundRect(rectF, 60, 60, mPaint);
}
@Override public void setAlpha(int alpha) { }
@Override public void setColorFilter(ColorFilter colorFilter) { }
@Override public int getOpacity() { return 0; }
// 下面兩個方法回傳原圖尺寸,才能保證圖片完整呈現
@Override public int getIntrinsicWidth() { return bitmap.getWidth(); }
@Override public int getIntrinsicHeight() { return bitmap.getHeight(); }
}
圓形版本:
/**
* 圓形圖片(頭像)
*/
public class CircleDrawable extends Drawable {
private int mWidth;
private RectF rectF;
private Paint mPaint;
private Bitmap bitmap;
public CircleDrawable(Bitmap bitmap) {
this.bitmap = bitmap;
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(bitmapShader);
rectF = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
mWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
rectF = new RectF(left, top, right, bottom);
mWidth = (int) Math.min(rectF.width(), rectF.height());
}
@Override
public void draw(Canvas canvas) {
canvas.drawCircle(rectF.left + mWidth / 2, rectF.top + mWidth / 2, mWidth / 2, mPaint);
}
@Override public void setAlpha(int alpha) { }
@Override public void setColorFilter(ColorFilter colorFilter) { }
@Override public int getOpacity() { return 0; }
// 回傳 mWidth 才能正常顯示完整圓形頭像,否則大圖會被裁掉只留左上角
@Override public int getIntrinsicWidth() { return mWidth; }
@Override public int getIntrinsicHeight() { return mWidth; }
}
呼叫方式:
Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.cute);
// 圓角 Drawable
imageView1.setImageDrawable(new RoundRectImageDrawable(b));
// 圓形 Drawable
imageView2.setImageDrawable(new CircleDrawable(b));
Shape 專門用來畫幾何圖形,易用又輕量,通常用 XML 定義後放在 res/drawable 目錄下。用 <shape> 標籤定義出來的其實是 GradientDrawable。
Shape 是抽象類,draw(Canvas canvas, Paint paint) 必須實作,onResize(float width, float height) 也是關鍵方法。它有五個子類:
| 子類 | 說明 |
|---|---|
| RectShape | 矩形、直角矩形、圓角矩形 |
| OvalShape | 橢圓形、圓形 |
| PathShape | 任意路徑構成的線形 |
| RingShape | 環形、環形進度條 |
| LineShape | 線形、實線、虛線 |
| ArcShape | 弧形 |
Shape 的通用屬性:
| 屬性 | 值說明 |
|---|---|
| shape | 根標籤,可為 rectangle / oval / ring / line。ring 另有 innerRadius(內環半徑)、innerRadiusRatio、thickness(厚度)、thicknessRatio、useLevel 等 |
| corners | radius、topLeftRadius、topRightRadius…… |
| gradient | 漸層:startColor、centerColor、endColor、angle(linear 時表示漸變角度)、type(linear / radial / sweep)…… |
| padding | left、top、right、bottom |
| size | width、height,決定 Shape 的寬高;不設定則由 View 的寬高決定 |
| solid | color,填充色 |
| stroke | 邊線:width、color、dashWidth(虛線寬度)、dashGap(虛線間距) |
舉個例子,圓角按鈕背景完全不必麻煩美工出圖:
<?xml version="1.0" encoding="utf-8"?>
<!-- shape 屬性設定形狀,這裡是矩形,也可設為 oval -->
<shape android:shape="rectangle"
xmlns:android="https://schemas.android.com/apk/res/android">
<!-- 圓角半徑 -->
<corners android:radius="8dp" />
<!-- 填充顏色 -->
<solid android:color="#da87ef" />
<!-- 尺寸 -->
<size android:height="100dp" android:width="100dp" />
<!-- 內距 -->
<padding android:bottom="8dp" android:left="8dp"
android:right="8dp" android:top="8dp" />
<!-- 邊線,這裡用虛線 -->
<stroke android:color="@color/gray" android:dashGap="1dp"
android:dashWidth="1dp" android:width="1dp" />
<!-- 漸層,需要時取消註解 -->
<!--
<gradient android:centerColor="@color/green"
android:endColor="@color/yellow"
android:gradientRadius="50dp"
android:startColor="@color/blue"
android:type="radial" />
-->
</shape>
效果如下:

這兩種需要用程式碼繪製,能畫出更自由的幾何形狀:

ShapeDrawable shapeDrawable = null;
// Path 菱形
Path p = new Path();
p.moveTo(50, 0);
p.lineTo(0, 50);
p.lineTo(50, 100);
p.lineTo(100, 50);
p.lineTo(50, 0);
p.close();
PathShape ps = new PathShape(p, 100, 100);
shapeDrawable = new ShapeDrawable(ps);
shapeDrawable.setBounds(0, 0, 100, 150);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setColor(Color.CYAN);
imageViewShapePath.setBackgroundDrawable(shapeDrawable);
// Arc:初始 225 度,掃過 270 度。0 度在右側水平位置
ArcShape arcShape = new ArcShape(225, 270);
shapeDrawable = new ShapeDrawable(arcShape);
shapeDrawable.setBounds(0, 0, 200, 200);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setColor(Color.BLUE);
imageViewShapeArc.setBackgroundDrawable(shapeDrawable);
// 環形效果:改用 STROKE 樣式
arcShape = new ArcShape(45, 270);
shapeDrawable = new ShapeDrawable(arcShape);
shapeDrawable.setBounds(0, 0, 200, 200);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
shapeDrawable.getPaint().setColor(Color.RED);
imageViewShapeRing.setBackgroundDrawable(shapeDrawable);
ShapeDrawable 是純程式碼路線:把 Shape 物件放進 ShapeDrawable,再設定畫筆樣式。當 Drawable 尺寸變化時,會呼叫 ShapeDrawable.ShaderFactory 產生對應的 Shader。可用的 Shader 有 BitmapShader、ComposeShader、LinearGradient、RadialGradient、SweepGradient。
// BitmapShader
shapeDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new BitmapShader(b, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}
});
// LinearGradient:顏色數量不限,可以給任意多個色階
shapeDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, 0, width, height,
new int[]{ Color.RED, Color.BLACK, Color.BLUE },
null, Shader.TileMode.CLAMP);
}
});
// SweepGradient:注意色值陣列與位置陣列的數量必須一致
shapeDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new SweepGradient(width / 2, height / 2,
new int[]{ Color.RED, Color.YELLOW, Color.BLUE, Color.CYAN },
new float[]{ 0.1f, 0.3f, 0.7f, 1.0f });
}
});
BitmapDrawable 是對 bitmap 的一層封裝,可以控制平鋪、拉伸或保持原尺寸。像那種需要反覆鋪陳的小圖,讓美工給一張很小的素材,交給 BitmapDrawable 重複渲染即可。
| 屬性 | 說明 |
|---|---|
| src | 只能是圖片,不能是 XML 定義的 drawable |
| gravity | 對齊方式 |
| antialias | 是否開啟抗鋸齒 |
| dither | 是否抖動 |
| filter | 是否對圖片做濾波 |
| tileMode | repeat、mirror、clamp(邊緣拉伸)、disable |
| tint | 著色 |
| mipmap | 是否可使用 mipmap(API >= 17) |
| tileModeX / tileModeY | API >= 21 |
| tintMode | API >= 21 |
XML 方式,在 res/drawable 下定義:
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
android:antialias="true"
android:dither="true"
android:src="@mipmap/cute"
android:tileMode="mirror" />
程式碼方式:
Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.cute);
BitmapDrawable bd = new BitmapDrawable(getResources(), b);
bd.setAntiAlias(true);
bd.setTileModeXY(Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
ivBitmapPic.setImageDrawable(bd);
.9 圖最大的特點是拉伸時不會變形失真,但它只用於需要拉伸的場景。同樣可以在 res/drawable 下用 <nine-patch> 標籤定義,前提是素材必須是 .9.png。Android SDK 的 tools 目錄下自帶了 .9 圖製作工具。
android.graphics.Picture 不儲存實際像素,只記錄繪製過程,包成 PictureDrawable(Picture p) 後即可使用。
實務提醒:PictureDrawable 在不少機型上顯示不出來,需要把對應 Activity 的硬體加速關掉:
android:hardwareAccelerated="false"。
Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.cute);
Paint paint = new Paint();
paint.setTextSize(30);
Picture p = new Picture();
Canvas c = p.beginRecording(b.getWidth(), b.getHeight());
c.drawBitmap(b, 0, 0, paint);
c.drawText("PictureDrawable", 20, 50, paint);
p.endRecording();
PictureDrawable drawable = new PictureDrawable(p);
ivPicDrawable.setImageDrawable(drawable);
ColorDrawable 有兩個地方可以定義:drawable 目錄和 values 目錄。
放在 drawable 目錄:
<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="https://schemas.android.com/apk/res/android"
android:color="#ff0000" />
放在 values 目錄:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<drawable name="colorDrawable">#000000</drawable>
</resources>
ImageView、ImageButton、Drawable 與 Paint 都可以套用 ColorFilter,它有三個子類:
| 子類 | 說明 |
|---|---|
| ColorMatrixColorFilter | 指定一個 4×5 的 ColorMatrix |
| LightingColorFilter | RGB 通道強度變換 |
| PorterDuffColorFilter | RGB 混色效果,共 18 種模式 |
// ColorMatrix:調整各通道權重
private void setArgb(int alpha, int red, int green, int blue) {
ColorMatrix colorMatrix = new ColorMatrix(new float[]{
red, 0, 0, 0, 0,
0, green, 0, 0, 0,
0, 0, blue, 0, 0,
0, 0, 0, alpha, 0
});
drawable.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
view.postInvalidate();
}
LightingColorFilter,公式為 (mul × 原色值 + add) % 255:
// 過濾掉 blue 通道,並整體增亮 55
drawable.setColorFilter(new LightingColorFilter(0x0000ff, 0x000055));
PorterDuffColorFilter:
// mutate() 讓同一個 Drawable 在不同控制項上呈現不同效果
drawable.mutate().setColorFilter(
new PorterDuffColorFilter(0x0000ff, PorterDuff.Mode.ADD)); // 共 18 種模式
GradientDrawable linearGradient = new GradientDrawable();
linearGradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
// 另有 RADIAL_GRADIENT、SWEEP_GRADIENT
// XML 只支援 startColor / centerColor / endColor,程式碼可以給任意多個色值(API 16+)
linearGradient.setColors(new int[]{ 0xff0000, 0xff0001, 0x000ff1, 0xff2310, 0x12ff00 });
linearGradient.setShape(GradientDrawable.RECTANGLE); // 另有 OVAL、LINE、RING
view.setBackground(linearGradient); // API 16+
Android 5.0 之後引入了 Tint 機制:android:backgroundTint、android:tint 及對應的 tintMode。其中 ImageView 兩者都有,其他控制項通常只有 background 的 tint。
LayerDrawable、LevelListDrawable 與 TransitionDrawable 有相似之處:都在管理多個 Drawable 的呈現。其中 TransitionDrawable 是 LayerDrawable 的子類,只管兩個 Drawable。不過從繼承體系看,LevelListDrawable 和 StateListDrawable 血緣更近,效果也相似。
在 res/drawable 下定義,可以依 View 的狀態(pressed、focused、checked 等)顯示不同的 Drawable。按鈕按下時換背景就是最典型的用法。
注意:正常狀態的那一項要放在最後。StateListDrawable 是從上往下逐一比對的,一旦匹配到就採用,順序錯了就會看不到狀態變化。
LayerDrawable 是多層結構,每一層都能單獨控制,从而实现一些組合效果:
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/mv" android:id="@+id/l1"
android:left="20dp" android:top="20dp" />
<item android:drawable="@mipmap/mv" android:id="@+id/l2"
android:left="40dp" android:top="40dp" />
<item android:id="@+id/l3" android:left="60dp" android:top="60dp">
<shape>
<gradient android:centerColor="@color/blue" />
</shape>
</item>
</layer-list>
為每一層指定 id 之後,就能在程式碼裡針對性地控制它。例如下面把最上層隱藏掉:

DisplayMetrics dm = getResources().getDisplayMetrics();
Drawable[] ds = new Drawable[3];
ds[0] = getResources().getDrawable(R.mipmap.mv);
ds[1] = getResources().getDrawable(R.mipmap.mv);
ds[2] = getResources().getDrawable(R.mipmap.mv);
LayerDrawable layerDrawable = new LayerDrawable(ds);
// 第一個參數是層索引
layerDrawable.setLayerInset(0, 0, 0, (int)(20 * dm.density), (int)(20 * dm.density));
layerDrawable.setLayerInset(1, 0, 0, (int)(40 * dm.density), (int)(40 * dm.density));
layerDrawable.setLayerInset(2, 0, 0, (int)(60 * dm.density), (int)(60 * dm.density));
imageViewLayer.setImageDrawable(layerDrawable);
LevelListDrawable 依 level 的數值區間來決定顯示哪一項:
<!-- 每個 item 只在特定的 level 區間內顯示 -->
<level-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/level_child" android:minLevel="0" android:maxLevel="10" />
<item android:drawable="@drawable/level_child1" android:minLevel="11" android:maxLevel="20" />
<item android:drawable="@drawable/level_child2" android:minLevel="21" android:maxLevel="30" />
<item android:drawable="@drawable/level_child3" android:minLevel="31" android:maxLevel="40" />
<item android:drawable="@drawable/level_child4" android:minLevel="41" android:maxLevel="50" />
</level-list>
拖動 SeekBar 改變 level 值,畫面就會在不同的子 Drawable 之間切換:

TransitionDrawable 繼承自 LayerDrawable,但只能裝兩個子 Drawable。切換時會產生漸變動畫,視覺效果很不錯。先定義資源:
<transition xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/level_child4" />
<item android:drawable="@drawable/level_child5" />
</transition>
程式碼中觸發,參數是動畫時長(毫秒),兩個方法分別對應正向與反向漸變:
transitionDrawable.startTransition(500);
transitionDrawable.reverseTransition(500);
效果如下:

ClipDrawable、InsetDrawable、RotateDrawable 與 ScaleDrawable 都是 DrawableWrapper 的子類。它們自身只能包一個子 Drawable,透過對子 Drawable 做裁剪、內縮、旋轉、縮放來實現效果。
用 <clip> 標籤定義,放在 res/drawable 目錄:
<!-- 水平方向裁剪,由右到左,作用對象是 gradient_progress -->
<clip xmlns:android="https://schemas.android.com/apk/res/android"
android:clipOrientation="horizontal"
android:drawable="@drawable/gradient_progress_h"
android:gravity="left" />
<!-- 圖片由四周向中心擴散,或反向聚攏 -->
<clip xmlns:android="https://schemas.android.com/apk/res/android"
android:clipOrientation="horizontal|vertical"
android:drawable="@mipmap/mv"
android:gravity="center" />
容器類 Drawable 一律靠 setLevel(int level) 控制,level 的範圍是 [0, 10000]:
imageView.getDrawable().setLevel(10000);
效果圖:

InsetDrawable 用來為背景 Drawable 加上「內縮邊距」,概念類似 padding。用 <inset> 標籤包住一個 Drawable,再設定四邊距:
<inset xmlns:android="https://schemas.android.com/apk/res/android"
android:drawable="@drawable/inset_shape"
android:insetBottom="20dp"
android:insetLeft="20dp"
android:insetRight="20dp"
android:insetTop="20dp" />
用 <rotate> 標籤定義,實現旋轉效果,比如指針轉盤:
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
android:drawable="@mipmap/mv"
android:fromDegrees="0"
android:toDegrees="180"
android:pivotX="50%"
android:pivotY="50%"
android:visible="true" />
<!-- pivotX / pivotY 中的 %p 表示相對於父控制項的百分比 -->
上面定義了一張從 0° 旋轉到 180°、以自身中心為軸的圖:

用 <scale> 標籤定義縮放效果:
<scale xmlns:android="https://schemas.android.com/apk/res/android"
android:drawable="@mipmap/mv"
android:scaleWidth="50%"
android:scaleHeight="50%"
android:scaleGravity="right|top"
android:useIntrinsicSizeAsMinimum="false" />
<!-- scaleGravity 決定縮放後的對齊位置 -->

從 Android 5.0(API Level 21) 開始,系統提供了 VectorDrawable 與 AnimatedVectorDrawable。向量圖放大不失真、佔用記憶體小,學會並用好它對開發很有幫助。它只支援部分 SVG 規範,實務上通常是找現成的 SVG 素材轉換。
向量圖裡存的是繪製指令而非像素,其中大寫代表後面的參數是絕對座標,小寫代表相對座標。
| 指令 | 說明 |
|---|---|
| M | moveTo,移動繪製點 |
| L | lineTo,畫直線 |
| Z | close,把起點與終點閉合 |
| C | cubic bezier,三次貝茲曲線 |
| Q | quadratic bezier,二次貝茲曲線 |
| A | 圓弧,參數為 rx ry x-rotation large-arc-flag sweep-flag x y |

<vector xmlns:android="https://schemas.android.com/apk/res/android"
android:width="60dp"
android:height="60dp"
android:viewportWidth="600"
android:viewportHeight="600">
<group android:name="group"
android:pivotX="300.0"
android:pivotY="300.0"
android:rotation="0.0">
<!-- M 移到 300,70,接著 l 相對移動 0,-70 -->
<path android:name="v"
android:fillColor="@android:color/black"
android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
</group>
</vector>
AnimatedVectorDrawable 屬於屬性動畫的範疇,可以對向量圖的 group 或 path 屬性做動畫插值,實現形變、旋轉、路徑描繪等效果。
ViewPager 多頁滑動實作:support 套件配置與 FragmentPagerAdapter 完整示例
1、先加入 android support 套件 ViewPager、PagerTabStrip 這些類別都只有在 android support 套件中才提供,因此第一
Android 源碼中的適配器模式:從 Activity 類結構理解
適配器模式的核心意圖 適配器模式的目的,是把一個現有介面轉換成客戶端期待的介面,讓原本因介面不相容而無法協作的類別可以一起運作。它常見於框架設計,因為框架往往需要把不同子
Android 自定義圖形單點移動與縮放效果
單點拖曳在單指操作時,可透過 MotionEvent 取得目前座標,並更新檢視的 LayoutParams 邊距,讓圖形跟著手指移動。這種方式適合需要直接操控位置的簡單互
Android 拼圖游戲的設計邏輯,實例提高!
群英傳的最後一章。我大致的看了一下這個例子,發現鴻洋大神也做過,就參考兩個人的設計邏輯,感覺都差不多,就這樣實現起來了。 一、切圖工具類 我們九宮格嘛,肯定要一個切圖的