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

Android 中 shape 標簽與漸變色的系統梳理

編輯:關於 Android 程式設計

做 UI 時,很多效果其實不需要一張切圖,一個 shape 的 XML 就夠了。下面把 shape 的常用子標簽與漸變相關知識梳理一遍。

一、shape 的整体結構

shape 資源裡主要包括六塊:邊角(corners)、漸變(gradient)、大小(size)、內邊距(padding)、填充(solid)、描邊(stroke)。

二、corners:圓角

<corners
    android:radius=""
    android:topLeftRadius=""
    android:topRightRadius=""
    android:bottomLeftRadius=""
    android:bottomRightRadius=""/>

各值均為整數 dp,代表對應角的圓角半徑。注意 radius 是統一設置,一旦同時寫了單角半徑,以單角設置為準。

三、gradient:漸變填充

<gradient
    android:angle=""
    android:centerColor=""
    android:endColor=""
    android:startColor=""
    android:type=""
    android:gradientRadius=""/>

angle 表示漸變方向,必須是 45 的整數倍。當 angle 為 0 時漸變自左向右,隨角度逆時針旋轉,90 度時即為自下而上。

三個顏色分別是起始色、中間色與結束色,中間色可省略。若使用 type="radial" 的環形漸變,則必須提供 gradientRadius。

四、size 與 padding

<size android:width="" android:height=""/>

<padding
    android:left=""
    android:top=""
    android:right=""
    android:bottom=""/>

size 定義形狀的固有尺寸,padding 則定義內容區到四邊的內邊距。

五、solid 與 stroke

<solid android:color="color"/>
<stroke android:width="" android:color="" android:dashWidth="" android:dashGap=""/>

solid 是純色填充,stroke 是描邊,後者還支持虛線(dashWidth 與 dashGap 配合)。solid 與 gradient 互斥,二者只取其一。

六、android:shape 的四種取值

android:shape=["rectangle" | "oval" | "line" | "ring"]

  • rectangle:矩形,最常用。
  • oval:橢圓/圓形。
  • line:直線。
  • ring:環形,需配合 android:innerRadius 與 android:thickness 使用。

代碼裡若只寫 shape 而不指定,默認就是矩形。

七、代碼中的三種漸變

XML 裡配的漸變,在 Java 層對應三個 Shader 類:

  • LinearGradient:線性漸變,沿直線方向過渡。
  • RadialGradient:環形漸變,由中心半徑向外擴散。
  • SweepGradient:掃描漸變,繞一個中心點做角度掃描,視覺上很像雷達的掃描線。

需要動態改顏色時,也可以在代碼裡拿到 GradientDrawable 直接調 setColor()、setCornerRadius(),比重新寫多份 XML 靈活得多。

八、一個實用示例

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="45"
        android:startColor="#FF9900"
        android:centerColor="#FFFF00"
        android:endColor="#66FF00"/>
    <corners android:radius="8dp"/>
    <stroke android:width="1dp" android:color="#333333"/>
    <padding android:left="12dp" android:top="6dp" android:right="12dp" android:bottom="6dp"/>
</shape>

這一個文件同時用到了漸變填充、圓角、描邊與內邊距,把它掛到任意 View 的 background 上,就是一個帶漸變的圓角按鈕,全程零切圖。

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