在 Android 開發中,將方形圖片顯示為圓形頭像是常見需求。雖然可以使用第三方庫(如 Glide、Picasso 的 transformation),但若想僅依賴原生 XML 布局與 Drawable 資源即可實現,掌握自定義 Drawable 的寫法非常實用。
利用 ShapeDrawable 或 GradientDrawable 定義圓形形狀,並將其設置為 ImageView 的背景或前景,再配合 android:scaleType="centerCrop" 即可將方形圖片裁剪為圓形。
res/drawable/ 下創建 circle_mask.xml:<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="oval">
<size android:width="100dp" android:height="100dp" />
</shape><ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@drawable/your_square_avatar"
android:background="@drawable/circle_mask" />若專案已引入 Material Components 庫,可直接使用 ShapeableImageView,代碼更簡潔:
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@drawable/your_square_avatar"
app:shapeAppearanceOverlay="@style/CircleShape" />並在 styles.xml 定義:
<style name="CircleShape">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>通過原生 Drawable 或 Material Components 的 ShapeableImageView,無需引入額外圖片處理庫即可實現圓形頭像,輕量且高效。