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

Android 圖片覆蓋實作:用 RelativeLayout 疊上透明遮罩

編輯:關於 Android 程式設計

做相簿瀏覽器時,常需要在 Gallery 之上疊一層半透明遮罩或漸層陰影,讓下方圖片被柔化,或用來承載左右切換的提示圖示。這種「圖疊圖」的需求,用 RelativeLayout 的對齊屬性就能漂亮解決。

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/gallerylayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Gallery
        android:id="@+id/overview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/navigmaske"
        android:background="#0000"
        android:src="@drawable/a2"
        android:scaleType="fitXY"
        android:layout_alignTop="@id/overview"
        android:layout_alignBottom="@id/overview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

兩個關鍵屬性

layout_alignTop / layout_alignBottom:讓遮罩 ImageView 的上邊界對齊 Gallery 的上邊界、下邊界對齊 Gallery 的下邊界。這樣不論 Gallery 實際高度如何變化,遮罩都會精確貼合,不會多也不會少。這比寫死 layout_height="160dp" 穩健得多。

android:background="#0000" 與 android:src:背景設為全透明,前景放一張 PNG 透明圖(a2)。這裡的重點是「遮罩圖必須是帶 alpha 通道的 PNG」,若用 JPG 就完全沒有透明效果,會把底下的 Gallery 蓋死。

疊放順序決定誰在上面

RelativeLayout 中後宣告的子元素會畫在上方。範例裡 ImageView 寫在 Gallery 之後,所以遮罩會蓋住 Gallery;若順序顛倒,遮罩就會被圖片蓋住而看不到。這點與 FrameLayout 的行為一致。

常見延伸應用

  • 漸層遮罩:把 ImageView 換成一張上下漸層的 PNG,或用 View 搭配 shape 的 <gradient> 定義,做出文字區域的漸層保護。
  • 點擊穿透:若遮罩只是視覺效果、不該攔截觸控,加上 android:clickable="false" 並確保它沒有背景可聚焦,事件才會往下傳給 Gallery。
  • 置中覆蓋:若只想蓋住中間區域,可改用 layout_centerInParent="true" 搭配固定寬高,或用 ConstraintLayout 的百分比寬度更精準。

整體來說,「RelativeLayout + alignTop/alignBottom + 透明 PNG」是實作圖片覆蓋最直覺的組合,不必自訂 View 就能達到像素級對齊。

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