Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

用 shape.xml 打造 Android 漸層背景的各種寫法

編輯:初階開發

想為 Android 的 View 加上漸層(漸變)背景,最簡單的方式就是寫一個 shape 的 drawable XML,放到 res/drawable-*/ 目錄下即可。本文整理從基礎到進階的幾種常見寫法。

最基礎的線性漸層

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#3A3C39"
        android:endColor="#181818"
        android:angle="270" />
    <corners android:radius="0dp" />
</shape>

使用時只需在版面中指定背景:

android:background="@drawable/shape_background_grey"

其中 android:angle 代表漸層方向:270 表示由上而下,180 表示由右到左,預設(0)則是由左到右。

加入 centerColor 的三段漸層

<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient android:angle="0"
        android:startColor="#FFdaf3fc"
        android:centerColor="#FFd4e9a9"
        android:endColor="#FFdaf3fc" />
</shape>

加上 android:centerColor 後,就能做出「起色 → 中間色 → 終色」的三段式漸層,視覺層次更豐富。

放射狀漸層

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:type="radial" android:gradientRadius="250"
        android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>

把 android:type 設為 radial 就會變成由中心向外擴散的放射狀漸層,此時 android:gradientRadius 用來指定漸層半徑,是必填的關鍵參數。

加上邊距與圓角的完整範例

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#509245" android:centerColor="#3e8532"
        android:endColor="#509245" android:type="linear" android:angle="90"
        android:centerX="0.5" android:centerY="0.5" />
    <padding android:left="7dp" android:top="7dp" android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>

各節點的意義

  • android:shape:設定圖形外形,常見有 rectangle(矩形)、oval(橢圓/圓形)等,上述範例為矩形。
  • gradient:設定漸層,包括起色 startColor、終色 endColor、中間色 centerColor、漸層角度 angle(90 度為上下漸層,0 度為左右漸層)、類型 type(linear 線性、radial 放射狀),以及放射狀的中心座標 centerX/centerY 與半徑 gradientRadius。
  • padding:設定內容的上下左右邊距。
  • corners:設定四邊圓角半徑 radius。

只要靈活組合這幾個節點,就能變化出各式漂亮的漸層背景,而不需要額外準備圖片素材。

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