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

給 ImageView 加邊框最簡單的兩種做法(純 XML)

編輯:Android 程式設計入門

給 ImageView 加個 3dp 的灰色邊框,常見做法有兩種「重」方案:自定義 MyImageView 繼承 ImageView 并在 onDraw 里畫 canvas;或者准備一張帶邊框的背景圖。

其實完全不需要這么麻煩——用一個 shape 定義的 XML 背景,配合 padding 就能搞定,既不用建派生類,也不用準備素材。

做法一:shape 背景 + padding

新建 res/drawable/bg_border.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 內部填充色 -->
    <solid android:color="#EEEEEE" />
    <!-- 邊框:寬度 3dp,顏色灰色 -->
    <stroke android:width="3dp" android:color="#EEEEEE" />
    <!-- 圓角半徑,設 0 即直角 -->
    <corners android:radius="0dp" />
    <padding android:left="0dp" android:top="0dp"
        android:right="0dp" android:bottom="0dp" />
</shape>

然后在布局里引用這個背景,關鍵是 android:padding——它決定圖片內容與邊框之間的距離:

<ImageView
    android:id="@+id/iv_thumbnail"
    android:layout_width="63dp"
    android:layout_height="63dp"
    android:background="@drawable/bg_border"
    android:padding="3dp" />

做法二:更完整的 shape 模板

如果希望內部透明、只留邊框(比如做頭像描邊),把 solid 換成透明色即可:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- 設置邊框的大小和顏色 -->
    <stroke android:width="1dp" android:color="@color/black" />

    <!-- 設置圖形內的顏色,此處為透明 -->
    <solid android:color="@android:color/transparent" />

    <!-- 定義圓角弧度;做圓形圖像時把四個半徑設為寬高的一半 -->
    <corners android:radius="0dp" />

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

想要正圓形邊框,把 corners 拆成四角分別設置,半徑取尺寸的一半:

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

    <stroke android:width="3.5dip" android:color="@color/white" />
    <solid android:color="@android:color/transparent" />

    <corners
        android:bottomLeftRadius="75dp"
        android:bottomRightRadius="75dp"
        android:topLeftRadius="75dp"
        android:topRightRadius="75dp" />
</shape>

幾個小提醒

  • android:padding 必須大於 stroke 的寬度,邊框才不會被圖片內容蓋住。
  • 如果邊框顏色需要動態變化(比如選中態),可以再用 selector 包一層,配合 state_selected 切換不同 shape。
  • shape 也可以用代碼加載:getResources().getDrawable(R.drawable.bg_border),便于運行時修改 stroke 顏色。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved