編輯:Android 技術基礎
從本節開始,我們進入繪圖與動畫的基礎知識,為後面的自訂控制項打地基。第一站先把 Android 的 Drawable 體系掃一遍——官方提供了多達 13 種 Drawable,接下來三節我們逐一走過。
- Drawable 分兩類:一類是一般的圖片資源,在 Android Studio 中通常放在 res/mipmap 目錄(這點和過去的 Eclipse 不同);如果把專案切換成 Android 檢視,直接往 mipmap 丟圖,AS 會自動幫你分好 hdpi、xhdpi 等密度版本。另一類是以 XML 撰寫的 Drawable 資源,一般放在 res/drawable 目錄,最常見的就是按鈕點擊切換用的 selector。
- XML 中用 @mipmap 或 @drawable 引用,例如 android:background = "@mipmap/iv_icon_zhu" 或 "@drawable/btn_back_selector"。Java 中則用 getResources().getDrawable(R.mipmap.xxx);如果想取得某個控制項目前的背景,直接呼叫 view.getBackground() 也可以拿到 Drawable 物件。
- Drawable 的資源名稱有命名規範:只能使用 [a-z0-9_.],也就是小寫字母、數字、底線與點,而且不能以數字開頭,否則會直接編譯失敗(Invalid file name: must contain only [a-z0-9_.])。小寫!小寫!小寫!這件事真的說三遍都不嫌多。
前提準備好,開始逐一認識這 13 種 Drawable。
最單純的一種。把 ColorDrawable 畫到 Canvas 上時,它會用一種固定顏色填滿 Paint,於是畫布上就出現一塊單色區域。
ColorDrawable drawable = new ColorDrawable(0xffff2200); txtShow.setBackground(drawable);
<?xml version="1.0" encoding="utf-8"?> <color xmlns:android="https://schemas.android.com/apk/res/android" android:color="#FF0000"/>
實務上這種寫法反而不常見,更普遍的做法是把顏色集中管理。
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="material_grey_100">#fff5f5f5</color> <color name="material_grey_300">#ffe0e0e0</color> <color name="material_grey_50">#fffafafa</color> <color name="material_grey_600">#ff757575</color> <color name="material_grey_800">#ff424242</color> <color name="material_grey_850">#ff303030</color> <color name="material_grey_900">#ff212121</color> </resources>
XML 中用 @color/xxx 引用;Java 中則是:
int mycolor = getResources().getColor(R.color.mycolor); btn.setBackgroundColor(mycolor);
PS:如果你直接在 Java 裡寫顏色值,一定要帶上透明度前綴,例如 0xff123456。漏掉的話系統會當成完全透明,看起來就像沒設定一樣。
例如 Color.BLACK(黑)、BLUE(藍)、CYAN(青)、GRAY(灰)、GREEN(綠)、RED(紅)、WHITE(白)、YELLOW(黃)。
btn.setBackgroundColor(Color.BLUE);
也可以取得系統資源顏色再套用:
int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light); btn.setBackgroundColor(getcolor);
XML 中則寫 android:background="@android:color/black"。
Android 用一個 int 表示顏色,通常是十六進位(0x 開頭)。完整的顏色值由透明度 alpha 與 RGB 三原色組成,以「#」起始,依序為:透明度-紅-綠-藍,支援 #RGB、#ARGB、#RRGGBB、#AARRGGBB 四種寫法。每個成分佔一個位元組(8 bit),取值範圍 0 到 255。
在 XML 中可以省略透明度,但在 Java 中必須明確寫出,省略會被視為全透明。這也是為什麼 0xFF0000 看起來是紅色卻什麼都畫不出來——正確寫法是 0xFFFF0000。
示例(參數依序為透明度、紅、綠、藍):
txtShow.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));
也就是 .9 圖。前面 1.6 節已經仔細講過 .9 圖的製作原理:Android Framework 在繪製時會套用高效的圖形拉伸演算法,我們不需要額外處理,就能讓圖片依內容自適應拉伸。
使用 Android Studio 時有幾個實務眉角:
- 1. .9 圖不能放在 mipmap 目錄,必須放在 drawable 目錄。
- 2. AS 對 .9 圖的檢查比 Eclipse 嚴格——必須有黑色標記線,否則連編譯都不會過。有些第三方工具能產出沒有黑線的 .9 圖,在 Eclipse 上能用,換到 AS 就直接編譯失敗。網路上流傳一些去掉黑點的方法,有興趣可以試,但我覺得黑線沒那麼礙眼。
- 3. 從別人 apk 解壓出來拿 .9 素材時也會發現沒有黑線,同樣會報錯。想取得帶黑線的 .9 素材,必須反編譯 apk 而不是直接解壓,因為黑線資訊在編譯過程中被編進了特殊 chunk 裡。
接著兩個比較少用的寫法:
XML 定義 NinePatchDrawable
<!-- 參數依序為:引用的 .9 圖片、是否對位圖做抖動處理 --> <?xml version="1.0" encoding="utf-8"?> <nine-patch xmlns:android="https://schemas.android.com/apk/res/android" android:src="@drawable/dule_pic" android:dither="true"/>
用 Bitmap 包裝 .9 圖片
<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="https://schemas.android.com/apk/res/android" android:src="@drawable/dule_pic" android:dither="true"/>
形狀 Drawable,用來定義基本的幾何圖形(矩形、圓形、線段、環形等)。根元素是 <shape>,子節點不少,整理如下:
- ① <shape>:
- ~ visible:是否可見。
- ~ shape:形狀,可選 rectangle(矩形,含正方形)、oval(橢圓,含圓)、line(線段)、ring(環形)。
- ~ innerRadiusRatio:僅 ring 有效,內半徑佔整體半徑的比例;若設了 innerRadius 則此值被忽略。
- ~ innerRadius:僅 ring 有效,環的內半徑尺寸。
- ~ thicknessRatio:僅 ring 有效,環厚度佔半徑的比例。
- ~ thickness:僅 ring 有效,環的厚度(外半徑減內半徑)。
- ~ useLevel:僅 ring 有效,是否允許依 level 只顯示環的一部分。
- ② <size>:
- ~ width:形狀寬度。
- ~ height:形狀高度。
- ③ <gradient>:漸層,留到 GradientDrawable 再細說。
- ④ <solid>:
- ~ color:純色填充。注意:設了 solid 會覆蓋 gradient 的所有效果,兩者不要同時寫。
- ⑤ <stroke>:
- ~ width:邊框寬度。
- ~ color:邊框顏色。
- ~ dashWidth:虛線段長度。
- ~ dashGap:虛線間距。
- ⑥ <corners>:
- ~ radius:四角統一的圓角半徑。
- ~ topLeftRadius、topRightRadius、bottomLeftRadius、bottomRightRadius:分別指定四個角的圓角值,但這四個值要生效,就不能再寫 radius。
- ⑦ <padding>:
- left、top、right、bottom:分別是四個方向的內距。
使用示例:可以參考 2.3.1 TextView(文字框)詳解。

帶漸層區域的 Drawable,支援線性漸層、輻射漸層與掃描漸層三種。核心節點為 <gradient>,可選屬性如下:
- startColor:漸層起始色。
- centerColor:漸層中間色。
- endColor:漸層結束色。
- type:漸層類型,可選 linear(線性,可設角度)、radial(輻射,由中心向外擴散)、sweep(掃描/平鋪)。
- centerX:漸層中心的 x 座標,範圍 0 到 1。
- centerY:漸層中心的 y 座標,範圍 0 到 1。
- angle:僅 linear 有效,表示漸層角度,必須是 45 的倍數。
- gradientRadius:僅 radial 與 sweep 有效,其中 radial 必填,表示漸層半徑。
- useLevel:是否依 level 決定漸層顯示範圍。
程式碼示例:三種漸層的實作

先在 drawable 下建立三個檔案。
線性漸層 gradient_linear.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="90" android:centerColor="#FFEB82" android:endColor="#35B2DE" android:startColor="#DEACAB" /> <stroke android:dashGap="5dip" android:dashWidth="4dip" android:width="3dip" android:color="#fff" /> </shape>
輻射漸層 gradient_radial.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:innerRadius="0dip" android:shape="ring" android:thickness="70dip" android:useLevel="false"> <gradient android:centerColor="#FFEB82" android:endColor="#35B2DE" android:gradientRadius="70" android:startColor="#DEACAB" android:type="radial" android:useLevel="false" /> </shape>
掃描漸層 gradient_sweep.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://schemas.android.com/apk/res/android" android:innerRadiusRatio="8" android:shape="ring" android:thicknessRatio="3" android:useLevel="false"> <gradient android:centerColor="#FFEB82" android:endColor="#35B2DE" android:startColor="#DEACAB" android:type="sweep" android:useLevel="false" /> </shape>
版面配置一次掛上三個:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/txtShow1" android:layout_width="200dp" android:layout_height="100dp" android:background="@drawable/gradient_linear" /> <TextView android:id="@+id/txtShow2" android:layout_width="200dp" android:layout_height="200dp" android:background="@drawable/gradient_radial" /> <TextView android:id="@+id/txtShow3" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/gradient_sweep" /> </LinearLayout>
用 XML 做到這裡就差不多了。想畫更複雜的圖形,光靠 XML 遠遠不夠,得回到 Java 搭配 ShapeDrawable 與 PathEffect。以下範例整理自網路上的經典寫法:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private ShapeDrawable[] mDrawables;
private static Shader makeSweep() {
return new SweepGradient(150, 25, new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF0000 }, null);
}
private static Shader makeLinear() {
return new LinearGradient(0, 0, 50, 50,
new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF },
null, Shader.TileMode.MIRROR);
}
private static Shader makeTiling() {
int[] pixels = new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0 };
Bitmap bm = Bitmap.createBitmap(pixels, 2, 2, Bitmap.Config.ARGB_8888);
return new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
}
// 自訂 ShapeDrawable:同時畫填充與描邊
private static class MyShapeDrawable extends ShapeDrawable {
private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public MyShapeDrawable(Shape s) {
super(s);
mStrokePaint.setStyle(Paint.Style.STROKE);
}
public Paint getStrokePaint() {
return mStrokePaint;
}
@Override
protected void onDraw(Shape s, Canvas c, Paint p) {
s.draw(c, p);
s.draw(c, mStrokePaint);
}
}
public SampleView(Context context) {
super(context);
setFocusable(true);
float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };
RectF inset = new RectF(6, 6, 6, 6);
float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };
Path path = new Path();
path.moveTo(50, 0);
path.lineTo(0, 50);
path.lineTo(50, 100);
path.lineTo(100, 50);
path.close();
mDrawables = new ShapeDrawable[7];
mDrawables[0] = new ShapeDrawable(new RectShape());
mDrawables[1] = new ShapeDrawable(new OvalShape());
mDrawables[2] = new ShapeDrawable(new RoundRectShape(outerR, null, null));
mDrawables[3] = new ShapeDrawable(new RoundRectShape(outerR, inset, null));
mDrawables[4] = new ShapeDrawable(new RoundRectShape(outerR, inset, innerR));
mDrawables[5] = new ShapeDrawable(new PathShape(path, 100, 100));
mDrawables[6] = new MyShapeDrawable(new ArcShape(45, -270));
mDrawables[0].getPaint().setColor(0xFFFF0000);
mDrawables[1].getPaint().setColor(0xFF00FF00);
mDrawables[2].getPaint().setColor(0xFF0000FF);
mDrawables[3].getPaint().setShader(makeSweep());
mDrawables[4].getPaint().setShader(makeLinear());
mDrawables[5].getPaint().setShader(makeTiling());
mDrawables[6].getPaint().setColor(0x88FF8844);
PathEffect pe = new DiscretePathEffect(10, 4);
PathEffect pe2 = new CornerPathEffect(4);
mDrawables[3].getPaint().setPathEffect(new ComposePathEffect(pe2, pe));
MyShapeDrawable msd = (MyShapeDrawable) mDrawables[6];
msd.getStrokePaint().setStrokeWidth(4);
}
@Override
protected void onDraw(Canvas canvas) {
int x = 10;
int y = 10;
int width = 400;
int height = 100;
for (Drawable dr : mDrawables) {
dr.setBounds(x, y, x + width, y + height);
dr.draw(canvas);
y += height + 5;
}
}
}
}
這段程式碼用了 ShapeDrawable 與 PathEffect。前者是對基本圖形的包裝,包含 ArcShape、OvalShape、PathShape、RectShape、RoundRectShape;後者是路徑特效,包含 CornerPathEffect、DashPathEffect、DiscretePathEffect,可以做出複雜的邊框樣式,ComposePathEffect 則能把兩種效果串起來。
關於 GradientDrawable 就談到這裡。想更深入研究,可以參考 appium/android-apidemos 專案裡的相關範例。
本節先完成 ColorDrawable、NinePatchDrawable、ShapeDrawable、GradientDrawable 這四種。其中 Color、NinePatch、Shape 在前面都提過,這裡算是重新整理,但為了讓這份教程完整,還是完整寫過一遍。
其中 ShapeDrawable 與 GradientDrawable 是實務上最常被使用的兩種——按鈕、卡片、分割線、漸層背景幾乎都靠它們,建議把 <solid>、<stroke>、<corners>、<gradient> 這幾個子節點練到不用查文件也能寫出來。
Android 網路編程入門與 HTTP 協議完全解析
本節導讀 終於來到 Android 網路編程這一關鍵章節。前面我們寫的都是單機程式,難免有些意猶未盡。從本節開始,我們正式邁入網路開發的世界。接下來要掌握的內容包括:An
2.6.1 PopupWindow 懸浮視窗基本用法
前言 本節介紹的是最後一個用於顯示資訊的 UI 元件——PopupWindow(懸浮視窗)。想知道它長什麼樣?打開手機裡的 QQ,長按清單上的某一項,這時會彈出一個黑色
Paint API 之 ColorFilter(顏色過濾器):PorterDuffColorFilter(3-3)
本節引言: 本來打算今天不寫的,難得空閒還是寫吧。本節帶給大家的是 ColorFilter 的第三個子類:PorterDuffColorFilter。看到 PorterD
ContentProvider 入門:讀取系統資料與自訂內容提供者
ContentProvider 的作用ContentProvider 是 Android 四大元件之一,主要用於在不同應用程式之間安全地共用資料。它可以用來讀取聯絡人、簡