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

Android 基礎入門教學:13 種 Drawable 圖解 Part 1

編輯:關於 Android 程式設計

本節引言

從這節開始進入繪圖與動畫的基礎,目的是替後面的自訂 View 打地基。第一課先把 Drawable 這塊地翻一遍——Android 一共提供了 13 種 Drawable,我們一次看過去。


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_selctor";在 Java 裡則透過 getResources().getDrawable(R.mipmap.xxx) 取得。如果想拿到某個控制項目前的背景,直接呼叫該控制項的 getDrawable() 也可以。

還有一條容易被忽略的硬性規定:資源名稱必須符合 [a-z0-9_.],也就是只能用小寫字母、數字、底線與點,而且不能以數字開頭,否則編譯直接失敗並丟出 Invalid file name: must contain only [a-z0-9_.]。小寫、小寫、小寫——重要的事說三次。


1. ColorDrawable

最單純的一種。把 ColorDrawable 畫到 Canvas 上時,它會用一個固定顏色填滿 Paint,於是畫布上就出現一片純色。

① Java 中定義

ColorDrawable drawable = new ColorDrawable(0xffff2200);
txtShow.setBackground(drawable);

② XML 中定義

<!--?xml version=1.0 encoding=utf-8?-->
<color xmlns:android="https://schemas.android.com/apk/res/android"
    android:color="#FF0000" />

這兩種寫法實務上用得不多。更常見的是在 res/values 下開一個 color.xml,把專案用到的顏色集中管理:

③ 建立 color.xml

<!--?xml version=1.0 encoding=utf-8?-->
<resources>
    <color name="material_grey_50">#fffafafa</color>
    <color name="material_grey_100">#fff5f5f5</color>
    <color name="material_grey_300">#ffe0e0e0</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);

另外提醒一件事:在 Java 中直接寫顏色值時,前面一定要補上 0x,而且不能省掉 alpha。

int mycolor = 0xff123456;   // 正確
btn.setBackgroundColor(mycolor);

④ 使用系統預先定義好的顏色

內建的選擇不少: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"。

⑤ 用 Color.argb() 組出顏色

Android 用一個 int 表示顏色,習慣寫成十六進位、以 0x 開頭。完整的組成是「透明度 + 紅 + 綠 + 藍」,寫法可為 #RGB、#ARGB、#RRGGBB、#AARRGGBB,每個成分佔一個位元組(8 bit),範圍 0~255。

在 XML 中透明度可以省略,但在 Java 程式碼中省略就代表完全透明,顏色等於沒設。0xFF0000 想表達紅色卻什麼都不顯示,就是這個原因;正確寫法是 0xFFFF0000。

// 參數依序為:透明度、紅、綠、藍
txtShow.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));

2. NinePatchDrawable

就是 .9 圖。前面 1.6 節談九宮格切圖時已經詳細講過製作流程。Android Framework 在繪製點九圖時使用了高效的圖形優化演算法,我們不必額外處理,就能讓圖片拉伸時自動適應。

不過用 AS 時有幾個實務上的眉角:

1. 點九圖不能放 mipmap,必須放 drawable 目錄。

2. AS 要求 .9 圖必須帶黑線,否則連編譯都過不了。 有人拿某工具產出的無黑線 .9 圖在 Eclipse 上跑得好好的,換到 AS 就直接編譯失敗——AS 判定 .9 的標準是要有黑線或黑點。網路上有人分享過去黑線的方法,有興趣可以試試,但說真的,那條線真沒那麼礙眼。

3. 直接解壓 apk 拿到的 .9 素材同樣沒有黑線,也會報錯。 想要可用的素材,得用反編譯工具而不是單純解壓,這樣才會保留黑線。

接著看兩個比較少用的寫法。

XML 定義 NinePatchDrawable(參數依序為引用的 .9 圖、是否抖動處理):

<!--pic9.xml-->
<!--?xml version=1.0 encoding=utf-8?-->
<nine-patch xmlns:android="https://schemas.android.com/apk/res/android"
    android:dither="true"
    android:src="@drawable/dule_pic" />

用 Bitmap 包裝 .9 圖:

<!--pic9.xml-->
<!--?xml version=1.0 encoding=utf-8?-->
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:dither="true"
    android:src="@drawable/dule_pic"></bitmap>

3. ShapeDrawable

形狀 Drawable,用來定義基本的幾何圖形:矩形、圓形、線條、圓環、路徑等等。實作上它是一組 Shape 的包裝,常見的有 RectShape、OvalShape、RoundRectShape、PathShape、ArcShape。搭配 stroke、corners、solid 等子節點,就能畫出圓角按鈕、分隔線這類常見元件。


4. GradientDrawable

具備漸層區域的 Drawable,可做出線性漸層、放射漸層與掃掠漸層三種效果。核心節點是 <gradient>,屬性如下:

startColor:起始色。centerColor:中間色。endColor:結束色。type:漸層類型,可選 linear(線性,可設角度)、radial(由中心向四周發散)、sweep(掃掠式)。centerX / centerY:中間色座標,範圍 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:width="3dip"
        android:color="#fff"
        android:dashWidth="4dip"
        android:dashGap="5dip" />
</shape>

放射漸層 gradient_radial.xml:

<!--?xml version=1.0 encoding=utf-8?-->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadius="0dip"
    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:shape="ring"
    android:innerRadiusRatio="8"
    android:thicknessRatio="3"
    android:useLevel="false">
    <gradient
        android:centerColor="#FFEB82"
        android:endColor="#35B2DE"
        android:startColor="#DEACAB"
        android:type="sweep"
        android:useLevel="false" />
</shape>

在 activity_main.xml 中套用:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    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 搭配 Shader 與 PathEffect 的組合:

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);
        }

        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 負責包裝各種基本圖形(ArcShape、OvalShape、PathShape、RectShape、RoundRectShape);PathEffect 負責邊線特效(CornerPathEffect、DashPathEffect、DiscretePathEffect,還能用 ComposePathEffect 疊加),可以做出相當複雜的邊框。對這部分有興趣的,建議直接去翻 AOSP 的 apidemos 範例。


本節小結

這四種 Drawable 各有分工:ColorDrawable 管純色、NinePatchDrawable 管可拉伸的點九圖、ShapeDrawable 管幾何形狀、GradientDrawable 管漸層。下一節我們把 BitmapDrawable 開始的五個收尾。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved