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

Android 5.0 新特性實戰:Palette 取色、View 陰影、Tinting 著色與 Clipping 裁剪

編輯:關於 Android 程式設計

Android 5.0 LOAT(Lollipop)問世時,Google 端出了 Material Design 這套設計語言,俗稱「材料設計」。它不只是換了一套配色和圓角,而是帶來了一批全新的 API 與設計元素。本文挑其中最實用的四項——Palette 調色板、Z 軸陰影、Tinting 著色與 Clipping 裁剪——逐一拆解,並附上可直接運行的示例。

一、Palette:讓 App 主題色跟著內容走

5.0 之後,我們多了一個名為 Palette 的工具類,它能從一張 Bitmap 裡萃取主色,讓 App 的配色動態貼合當前頁面的視覺基調。想像一個圖片並列的清單頁,每一列的標題列背景都自動採用該圖片最合適的色調,整體看起來和諧、統一,而不是硬塞一個品牌色到處套。

Palette 會從圖片中擷取六種色調,命名與定位如下:

  • Vibrant:飽和明亮、最具活力,最適合當主色。
  • Vibrant dark:充滿活力但偏深的版本。
  • Vibrant light:充滿活力但偏亮的版本。
  • Muted:柔和、低飽和,適合大面積鋪底。
  • Muted dark:柔和的深色版。
  • Muted light:柔和的淺色版。

要在專案中使用,先在 Gradle 加上 support 庫依賴:

compile 'com.android.support:palette-v7:23.4.0'

用法非常直觀:把一張 Bitmap 交給 Palette.generate() 同步產生結果,或使用它提供的非同步回調版本避免卡住主執行緒;接著用 getter 取出需要的 Swatch 即可。每個色調都會被封裝成 Palette.Swatch,除了 getRgb(),還附帶 getTitleTextColor()、getBodyTextColor() 等對應的文字建議色,拿來配色幾乎不用自己調。

需要留意的是,六種色調並非永遠都有值。若圖片本身的色彩不夠豐富,某幾個 Swatch 會回傳 null,因此實務上一定要寫成「主色取不到就退回次要色」的防禦式邏輯。

下面這個範例會用背景圖的柔和色調去染色標題列,讓整列視覺融為一體:

列表項布局 item_list.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

ColorfulAdapter:把取色邏輯放進背景執行緒

從磁碟解碼圖片、再跑一次 Palette 分析,兩件事都不便宜,若在主執行緒做會造成明顯掉幀。因此範例用 AsyncTask 把整段流程移到背景,並用 SparseArray 快取已算好的結果,避免捲動時重複計算。

public class ColorfulAdapter extends ArrayAdapter<String> {

    private static final int[] IMAGES = {
            R.drawable.bricks, R.drawable.flower, R.drawable.grass,
            R.drawable.stones, R.drawable.wood, R.drawable.dog
    };

    private static final String[] NAMES = {
            "Bricks", "Flower", "Grass", "Stones", "Wood", "Dog"
    };

    private final SparseArray<Bitmap> mImages = new SparseArray<>(IMAGES.length);
    private final SparseArray<Palette.Swatch> mColors = new SparseArray<>(IMAGES.length);

    public ColorfulAdapter(Context context) {
        super(context, R.layout.item_list, NAMES);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.item_list, parent, false);
        }

        View root = convertView.findViewById(R.id.root);
        ImageView imageView = convertView.findViewById(R.id.image);
        TextView textView = convertView.findViewById(R.id.text);

        int imageId = IMAGES[position];
        textView.setText(NAMES[position]);

        if (mImages.get(imageId) == null) {
            // 尚未載入完成,先用中性色,稍後由背景任務回填
            textView.setTextColor(Color.BLACK);
            new ImageTask().execute(imageId);
        } else {
            imageView.setImageBitmap(mImages.get(imageId));
            Palette.Swatch swatch = mColors.get(imageId);
            if (swatch != null) {
                root.setBackgroundColor(swatch.getRgb());
                textView.setTextColor(swatch.getTitleTextColor());
            }
        }
        return convertView;
    }

    private static class ImageResult {
        final int imageId;
        final Bitmap image;
        final Palette.Swatch swatch;

        ImageResult(int imageId, Bitmap image, Palette.Swatch swatch) {
            this.imageId = imageId;
            this.image = image;
            this.swatch = swatch;
        }
    }

    private class ImageTask extends AsyncTask<Integer, Void, ImageResult> {
        @Override
        protected ImageResult doInBackground(Integer... params) {
            int imageId = params[0];

            // 縮小解碼尺寸,避免大圖把記憶體吃乾
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            Bitmap image = BitmapFactory.decodeResource(
                    getContext().getResources(), imageId, options);

            Palette palette = Palette.generate(image);
            Palette.Swatch selected = palette.getVibrantSwatch();
            if (selected == null) {
                selected = palette.getMutedSwatch();   // 退回柔和色
            }
            return new ImageResult(imageId, image, selected);
        }

        @Override
        protected void onPostExecute(ImageResult result) {
            mImages.put(result.imageId, result.image);
            mColors.put(result.imageId, result.swatch);
            notifyDataSetChanged();
        }
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GridView gridView = new GridView(this);
        gridView.setNumColumns(2);
        gridView.setAdapter(new ColorfulAdapter(this));
        setContentView(gridView);
    }
}

二、視圖與陰影:把 Z 軸加進來

Material Design 的核心手法之一是「擬物扁平化」:用陰影與光源營造層次,再搭配流暢的過場動畫,讓平面介面看起來像真實材質堆疊起來的紙片。

過去 UI 只有 X、Y 兩個軸,5.0 之後多了一條垂直於螢幕的 Z 軸。View 的 Z 值由兩個屬性相加而成:

Z = elevation + translationZ

其中 elevation 是靜態的高度值,通常在 XML 中宣告;translationZ 則可在程式碼中動態改寫,用來做動畫。兩者都是 API 21 才引入的屬性,在 5.0 以下的系統上設定 elevation 不會有任何效果。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@android:color/holo_blue_dark" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@android:color/holo_blue_dark"
        android:elevation="10dp" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@android:color/holo_blue_dark"
        android:elevation="20dp" />
</LinearLayout>

若想在執行期讓高度平滑過渡,用屬性動畫搭配 translationZ 最合適:

if (raised) {
    view.animate().translationZ(100f);
    raised = false;
} else {
    view.animate().translationZ(0f);
    raised = true;
}

三、Tinting 著色與 Clipping 裁剪

3.1 Tinting:不改原圖也能換色

Tinting 的用法極簡,在 XML 上寫 tint 與 tintMode 即可。它的本質是透過 Alpha 遮罩層重新計算每個像素的顏色,因此同一張圖 can 被染成各種色彩,不必準備多套切圖。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="add" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="multiply" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="screen" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="src_atop" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="src_in" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="10dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@color/colorAccent"
        android:tintMode="src_over" />
</LinearLayout>

3.2 Clipping:改寫一個 View 的外輪廓

裁剪可以改變 View 的外觀形狀,做法是自訂一個 ViewOutlineProvider 描述輪廓,再用 setOutlineProvider() 套到目標 View 上。下面把兩個 ImageView 分別裁成 10dp 圓角矩形與正圓。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image_rect"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:elevation="2dp" />

    <ImageView
        android:id="@+id/image_circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="20dp"
        android:elevation="2dp" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {

    private ImageView mRectView;
    private ImageView mCircleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRectView = findViewById(R.id.image_rect);
        mCircleView = findViewById(R.id.image_circle);

        ViewOutlineProvider roundRectOutline = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 10);
            }
        };

        ViewOutlineProvider ovalOutline = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, view.getWidth(), view.getHeight());
            }
        };

        mRectView.setOutlineProvider(roundRectOutline);
        mCircleView.setOutlineProvider(ovalOutline);
    }
}

這四個能力——動態取色、Z 軸陰影、非破壞性著色、輪廓裁剪——正好對應 Material Design 想傳達的「介面應該回應內容、也應該有物理層次」。把它們組合起來,很容易做出視覺細節遠勝舊版樣式的畫面。

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