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

Android shape 標籤用法全解析

編輯:關於 Android 程式設計

在 Android 開發中,shape 是一種強大的背景繪製工具,可以透過純 XML 定義矩形、橢圓、線、環等形狀,並為它們加上漸層、圓角、描邊等效果,無需依賴圖片資源。

一、shape 標籤的 XML 結構

此標籤的 XML 檔放在 res/drawable 資料夾下,基本結構如下:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle">

shape 屬性:android:shape 決定形狀,預設為矩形,可設為 rectangle(矩形)、oval(橢圓)、line(線性)、ring(環形)。

當 android:shape="ring" 時,可用的屬性有:

  • android:innerRadius:內環半徑。
  • android:innerRadiusRatio:以環寬比率表示內環半徑,例如設為 5 表示內環半徑等於環寬除以 5,預設為 9。
  • android:thickness:環的厚度。
  • android:thicknessRatio:以環寬比率表示厚度,例如設為 2 表示厚度為環寬除以 2,預設為 3。
  • android:useLevel:當作為 LevelListDrawable 使用時設為 true,否則為 false。

圓角 corners:

  • android:radius:四角統一圓角半徑。
  • android:topLeftRadius:左上角半徑。
  • android:topRightRadius:右上角半徑。
  • android:bottomLeftRadius:左下角半徑。
  • android:bottomRightRadius:右下角半徑。
<corners
    android:radius="8dp"
    android:topLeftRadius="5dp"
    android:topRightRadius="15dp"
    android:bottomLeftRadius="20dp"
    android:bottomRightRadius="25dp" />

漸層 gradient:

  • android:startColor:起始顏色。
  • android:endColor:結束顏色。
  • android:centerColor:漸層中間顏色。
  • android:angle:漸層角度(angle=0 時由左向右,逆時針旋轉,angle=90 時由下往上,須為 45 的整數倍)。
  • android:type:漸層類型,可取 linear(線性,預設)、radial(放射狀)、sweep(掃描式)。
  • android:useLevel:使用 LevelListDrawable 時設為 true(此時無漸層),false 則有漸層。
  • android:gradientRadius:漸層半徑,僅在 android:type="radial" 時使用。
  • android:centerX / android:centerY:漸層中心的相對座標位置。
<gradient
    android:startColor="#FFFF0000"
    android:endColor="#80FF00FF"
    android:angle="45" />

內邊距 padding(內容與邊的距離):

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

大小 size:android:width 與 android:height 分別設定寬與高。

<size android:width="600dp" />

內部填充 solid:android:color 設定填充顏色。

<solid android:color="#ffff9d77" />

描邊 stroke:

  • android:width:描邊寬度。
  • android:color:描邊顏色。
  • android:dashWidth:虛線寬度,為 0 時表示實線。
  • android:dashGap:虛線間隔。
<stroke
    android:width="2dp"
    android:color="#dcdcdc" />
</shape>

二、在布局中引用

將步驟一建立的檔作為 TextView 的背景即可:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ShapeTest"
        android:background="@drawable/gradient_box"
        android:textSize="24.0dp"
        android:textColor="@android:color/black" />
</LinearLayout>

透過靈活組合上述標籤,你就能用純代碼方式做出豐富多樣的介面背景效果。

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