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

Android 實現圓角邊框:shape 標籤的用法

編輯:關於 Android 程式設計

登錄框、卡片、標籤這類元素經常需要圓角。與其反覆切圖,不如用 XML 描述——Android 的 Drawable 系統提供了 shape 標籤,改起來比換圖片方便得多。

定義圓角背景

在 drawable-mdpi 目錄下新建一個 XML 文件(本例命名 corners_bg.xml):

<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#000000" />
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"/>
</shape>

兩個關鍵子元素:solid 指定填充色,這裡為了簡單用黑色;corners 描述四個角的圓弧半徑。

有個容易搞錯的細節:在 Android 的 corners 定義中,bottomRightRadius 對應的是左下角,bottomLeftRadius 對應的是右下角,命名與視覺位置是交叉的。如果四個角半徑相同,不必寫四遍,直接用簡化寫法即可:

<corners android:radius="5dp" />

在布局中引用

引用時寫 @drawable/corners_bg,不需要帶後綴:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <RelativeLayout
        android:id="@+id/login_div"
        android:layout_width="fill_parent"
        android:layout_height="150dip"
        android:padding="15dip"
        android:layout_margin="15dip"
        android:background="@drawable/corners_bg">
    </RelativeLayout>
</LinearLayout>

運行效果:

順帶認識幾個常用子元素

shape 的能力遠不止填充和圓角,掌握後能省下大量切圖工作:

<stroke> 畫邊框,可設置 color 與 width。做「白底灰框圓角按鈕」時,它與 corners 的組合是標準套路。

<gradient> 實現漸變填充,配合 startColor、endColor 與 angle 就能做出簡單的漸變背景。

<padding> 在 Drawable 層面定義內邊距,與 View 的 padding 屬性效果重疊但作用範圍不同。

需要注意的是,早期版本中 shape 的圓角不會自動裁剪子內容。如果要在圓角容器裡放圖片並讓圖片也跟著圓角,得靠 android:clipToOutline(API 21 及以上)或自定義 ImageView 實現。

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