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

為 View 加上邊框的三種做法

編輯:關於 Android 程式設計

給控制項(例如 TextureView、ImageView、任何 View)加上描邊,實務上有三條路。三種都能用,但成本與維護性差距不小。

方案一:用 9-patch 圖片

準備一張 .9.png,四邊是邊框、中間透明,設為背景即可。優點是視覺效果可以完全手繪控制(漸層、內陰影、雙層邊框都行);缺點是每組顏色、粗細都要各出一張圖,多密度還要各出多份,改設計稿時維護成本高。

方案二:自訂 View 用 Canvas 畫

覆寫 onDraw(),用 Paint.setStyle(Paint.Style.STROKE) 畫一個 Rect。優點是自由度最高,可以做出「只有某兩邊有框」這類特殊需求;缺點是要寫 Kotlin/Java、多一個自訂 View 類別,除錯與維護都比宣告式麻煩。

方案三:用 ShapeDrawable 宣告(推薦)

只寫 XML,速度快、佔用資源小、程式碼量最少,也最容易維護。以下以此為主。

步驟 1:定義 background.xml

放在 res/drawable/ 目錄下:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <stroke
        android:width="2dp"
        android:color="#0000AA" />
</shape>

步驟 2:在 View 上套用背景

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/background"
    android:padding="2dp">

    <TextureView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.android.camera.ui.RotateLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFF"
            android:textSize="22sp"
            android:background="#0000000" />

    </com.android.camera.ui.RotateLayout>

</RelativeLayout>

注意這裡有兩個關鍵:把 Drawable 設在 TextureView 的父容器 RelativeLayout 上,並且加上 android:padding="2dp"。原因是 TextureView 是一個特殊的 SurfaceView 類別,它直接佔滿自己的邊界,若把背景設在它身上,邊框會被內容蓋住;設在父容器並留出 padding,邊框才會露在內容外側。

shape 標籤的常用子元素

<shape android:shape="rectangle">      <!-- rectangle / oval / line / ring -->
    <corners android:radius="4dp" />   <!-- 圓角;也可分四角指定 -->
    <solid android:color="#FFFFFF" />  <!-- 填充色 -->
    <stroke
        android:width="2dp"
        android:color="#0000AA"
        android:dashWidth="4dp"
        android:dashGap="2dp" />       <!-- 虛線框 -->
    <gradient
        android:startColor="#FFFFFF"
        android:endColor="#CCCCCC"
        android:angle="270" />         <!-- 漸層 -->
    <padding
        android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
</shape>

把 <stroke> 換成 <gradient> 就能做漸層邊框,加上 <corners> 就是圓角框,加上 dashWidth / dashGap 就是虛線框——這些都不需要寫一行 Java。

該選哪一種?

純色或漸層的單純描邊,一律用方案三。需要「只有左邊有分隔線」這類 shape 無法表達的樣式,用方案二的 drawLine() 或自訂 Drawable。只有在設計稿要求特殊材質(例如木紋邊框、光影他很細緻的插畫框)時,才值得花成本做 9-patch。

一個實務小技巧:如果只是要「卡片感」,與其自己疊邊框,不如直接用 MaterialCardView 搭配 app:strokeColor 與 app:strokeWidth,它還免費附贈陰影與水波紋效果。

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