您可以將圖片裁剪成特定形狀,並在形狀周圍繪製陰影,營造出立體感。這項技巧可用於製作自訂圖形,例如大頭貼和產品縮圖,或顯示自訂形狀的商標。
如要顯示裁剪為形狀的圖片,您必須執行下列操作:
- 建立形狀。
- 將圖片裁剪成形狀。
版本相容性
這個實作方式需要將專案 minSDK 設為 API 級別 21 以上。
依附元件
建立形狀
以下程式碼會建立自訂形狀,可動態繪製及算繪圓角多邊形:
fun RoundedPolygon.getBounds() = calculateBounds().let { Rect(it[0], it[1], it[2], it[3]) } class RoundedPolygonShape( private val polygon: RoundedPolygon, private var matrix: Matrix = Matrix() ) : Shape { private var path = Path() override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { path.rewind() path = polygon.toPath().asComposePath() matrix.reset() val bounds = polygon.getBounds() val maxDimension = max(bounds.width, bounds.height) matrix.scale(size.width / maxDimension, size.height / maxDimension) matrix.translate(-bounds.left, -bounds.top) path.transform(matrix) return Outline.Generic(path) } }
程式碼的重點
RoundedPolygon.getBounds()
會在RoundedPolygon
類別上定義擴充功能函式,用於計算其邊界。RoundedPolygonShape
類別會實作Shape
介面,讓您在 Jetpack Compose 中定義自訂形狀 (圓角多邊形)。- 此形狀會使用
Matrix
管理縮放和平移作業,以便靈活算繪。 createOutline()
函式會採用RoundedPolygon
物件,並將其縮放及轉譯,以便符合指定大小,並傳回Outline
物件,描述要繪製的最終形狀。
將圖片裁剪成形狀
以下程式碼會將圖片裁剪為六邊形,並加入微妙的陰影,營造出深度感:
val hexagon = remember { RoundedPolygon( 6, rounding = CornerRounding(0.2f) ) } val clip = remember(hexagon) { RoundedPolygonShape(polygon = hexagon) } Box( modifier = Modifier .clip(clip) .background(MaterialTheme.colorScheme.secondary) .size(200.dp) ) { Text( "Hello Compose", color = MaterialTheme.colorScheme.onSecondary, modifier = Modifier.align(Alignment.Center) ) }
程式碼的重點
RoundedPolygon
和RoundedPolygonShape
物件用於定義並套用六邊形形狀至圖片。- 程式碼會使用
graphicsLayer
為圖片新增以高度為依據的陰影。這樣就能營造出深度感,並與背景區隔開來。 - 使用
remember
區塊可提升效能,因為這可確保形狀和裁剪定義只計算一次,並記住日後的 UI 重組作業。
結果
![六邊形中的狗,邊緣套用陰影](https://developer.android.com/static/develop/ui/compose/images/graphics/shapes/clip_with_shadow.png?hl=zh-tw)
包含此指南的集合
本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:
![](https://developer.android.com/static/images/quick-guides/collection-illustration.png?hl=zh-tw)
顯示圖片
瞭解如何運用明亮吸睛的視覺元素,為 Android 應用程式打造美觀的視覺效果。
有問題或意見回饋嗎?
請前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。