首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 佈局圓角被 ImageView 遮蓋問題的解決方案

     編輯:程式設計疑難解答

現象

父佈局設定 android:background="@drawable/bg_rounded" 實現圓角,加入 ImageView 後,圖片矩形邊緣覆蓋圓角。

原因

ImageView 預設繪製區域為矩形,且預設不裁剪子視圖,導致其內容超出父佈局圓角邊界。

解決方案

  1. 給 ImageView 同樣圓角背景:
    <ImageView
        android:background="@drawable/bg_rounded"
        android:scaleType="centerCrop"
        android:src="@drawable/your_image" />
    bg_rounded.xml:
    <shape xmlns:android="https://schemas.android.com/apk/res/android">
        <solid android:color="@android:color/transparent"/>
        <corners android:radius="16dp"/>
    </shape>
  2. 使用 CardView 包裹(推薦):
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="16dp"
        app:cardElevation="0dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:scaleType="centerCrop"
            android:src="@drawable/your_image" />
    </androidx.cardview.widget.CardView>
  3. 程式碼動態裁剪(API 21+):
    imageView.setClipToOutline(true);
    imageView.setOutlineProvider(ViewOutlineProvider.BACKGROUND);

最佳實踐

優先使用 CardView 或 MaterialCardView,統一管理圓角、陰影、邊框,代碼更簡潔且相容性佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved