Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

給 View 加邊框的三種做法,推薦第三種

編輯:Android 開發實例

給 TextureView、ImageView 這類控件加一圈描邊,看著簡單,真要做得乾淨卻要挑方法。常見的有三種思路。

方案一:9-patch 圖片

做一張四邊有框、中間透明的 .9.png,直接設為背景。效果最可控,但每種顏色、每種粗細都得各出一張圖,維護成本高。

方案二:自定義 View 用 Canvas 畫

繼承目標 View,在 onDraw 裡用 Paint 畫一個矩形描邊。靈活度最高,圓角、雙線、局部邊框都能畫,但需要額外寫一個類,代碼量也最大。

方案三:用 ShapeDrawable 寫 XML(推薦)

只寫一個 XML,代碼量最少、性能開銷最小,改起來也快,便於後續維護。

第一步:定義 background.xml

<?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>

如果還想要圓角,再加一個 corners 節點即可:

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

第二步:在布局中引用

<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>

兩個實操細節

示例裡並不是把 background 設在 TextureView 自己身上,而是設在它的父容器 RelativeLayout 上,同時配了 2dp 的 padding。原因是 TextureView 的內容會直接佔滿自身邊界,如果背景設在自己身上,描邊會被內容蓋住;放在父容器上並留出 padding,邊框才能真正顯示在外側。

另外注意 shape 的 stroke 是畫在 View 邊界內側的,粗細設置過大容易吃掉可視區域,一般 1dp 到 2dp 視覺效果最好。

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