Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Puoi adattare un'immagine a una forma ritagliata e disegnare ombre intorno al perimetro della forma per dare un'impressione tridimensionale. Questa tecnica è utile per creare design come avatar e miniature dei prodotti o per visualizzare loghi con forme personalizzate.
Per visualizzare un'immagine ritagliata in una forma, devi:
Crea la forma.
Ritaglia l'immagine in base alla forma.
Compatibilità delle versioni
Questa implementazione richiede che il valore minSDK del progetto sia impostato sul livello API 21 o superiore.
Dipendenze
Creare una forma
Il seguente codice crea una forma personalizzata che può disegnare e visualizzare dinamicamente un poligono arrotondato:
RoundedPolygon.getBounds() definisce una funzione di estensione per la classe
RoundedPolygon per calcolarne i limiti.
La classe RoundedPolygonShape implementa l'interfaccia
Shape,
consentendoti di definire una forma personalizzata (un poligono arrotondato) in Jetpack Compose.
La forma utilizza un Matrix per gestire le operazioni di ridimensionamento e traduzione per un rendering flessibile.
La funzione createOutline() prende un oggetto RoundedPolygon, lo ridimensiona e lo trasla in modo che rientri in una determinata dimensione e restituisce un oggetto Outline che descrive la forma finale da disegnare.
Ritagliare l'immagine in una forma
Il codice seguente ritaglia l'immagine in un esagono e aggiunge una sfumatura delicata per dare un'impressione di profondità:
Gli oggetti RoundedPolygon e RoundedPolygonShape vengono utilizzati per definire e applicare una forma esagonale all'immagine.
Il codice utilizza graphicsLayer per aggiungere all'immagine un'ombra basata sull'elevazione.
In questo modo viene creato un senso di profondità e separazione visiva dallo sfondo.
L'utilizzo dei blocchi remember ottimizza le prestazioni garantendo che le definizioni di forma e ritaglio vengano calcolate una sola volta e memorizzate per le ricostruzioni successive dell'interfaccia utente.
Risultati
Figura 1. Forma personalizzata applicata come clip.
Raccolte che contengono questa guida
Questa guida fa parte di queste raccolte di guide rapide selezionate che coprono obiettivi di sviluppo Android più ampi:
Visualizza immagini
Scopri le tecniche per utilizzare immagini brillanti e coinvolgenti per conferire un aspetto accattivante alla tua app per Android.
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-02-06 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-02-06 UTC."],[],[],null,["# Display an image clipped to a shape\n\n\u003cbr /\u003e\n\nYou can fit an image to a clipped shape, and draw shadows around the perimeter\nof the shape to impart a three-dimensional feel. This technique is useful for\ncreating designs such as avatars and product thumbnails, or displaying\nlogos with custom shapes.\n\nTo display an image clipped to a shape, you must do the following:\n\n- Create the shape.\n- Clip the image to the shape.\n\nVersion compatibility\n---------------------\n\nThis implementation requires that your project minSDK be set to API level 21 or\nhigher.\n\n### Dependencies\n\n### Kotlin\n\n\u003cbr /\u003e\n\n```kotlin\n implementation(platform(\"androidx.compose:compose-bom:2025.08.00\"))\n implementation(\"androidx.graphics:graphics-shapes:1.0.0-alpha05\")\n \n```\n\n\u003cbr /\u003e\n\n### Groovy\n\n\u003cbr /\u003e\n\n```groovy\n implementation platform('androidx.compose:compose-bom:2025.08.00')\n implementation 'androidx.graphics:graphics-shapes:1.0.0-alpha05'\n \n```\n\n\u003cbr /\u003e\n\nCreate a shape\n--------------\n\nThe following code creates a custom shape that can dynamically draw and render\na rounded polygon:\n\n\n```kotlin\nfun RoundedPolygon.getBounds() = calculateBounds().let { Rect(it[0], it[1], it[2], it[3]) }\nclass RoundedPolygonShape(\n private val polygon: RoundedPolygon,\n private var matrix: Matrix = Matrix()\n) : Shape {\n private var path = Path()\n override fun createOutline(\n size: Size,\n layoutDirection: LayoutDirection,\n density: Density\n ): Outline {\n path.rewind()\n path = polygon.toPath().asComposePath()\n matrix.reset()\n val bounds = polygon.getBounds()\n val maxDimension = max(bounds.width, bounds.height)\n matrix.scale(size.width / maxDimension, size.height / maxDimension)\n matrix.translate(-bounds.left, -bounds.top)\n\n path.transform(matrix)\n return Outline.Generic(path)\n }\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/graphics/ShapesSnippets.kt#L353-L375\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- `RoundedPolygon.getBounds()` defines an extension function on the [`RoundedPolygon`](/reference/kotlin/androidx/graphics/shapes/RoundedPolygon) class to calculate its bounds.\n- The `RoundedPolygonShape` class implements the [`Shape`](/reference/kotlin/androidx/compose/ui/graphics/Shape) interface, allowing you to define a custom shape (a rounded polygon) in Jetpack Compose.\n- The shape uses a [`Matrix`](/reference/kotlin/androidx/compose/ui/graphics/Matrix) to manage scaling and translation operations for flexible rendering.\n- The `createOutline()` function takes a `RoundedPolygon` object, scales and translates it to fit within a given size, and returns an [`Outline`](/reference/kotlin/androidx/compose/ui/graphics/Outline) object that describes the final shape to be drawn.\n\nClip the image to a shape\n-------------------------\n\nThe following code crops the image to a hexagon, and adds a subtle drop\nshadow to provide a sense of depth:\n\n\n```kotlin\nval hexagon = remember {\n RoundedPolygon(\n 6,\n rounding = CornerRounding(0.2f)\n )\n}\nval clip = remember(hexagon) {\n RoundedPolygonShape(polygon = hexagon)\n}\nBox(\n modifier = Modifier\n .clip(clip)\n .background(MaterialTheme.colorScheme.secondary)\n .size(200.dp)\n) {\n Text(\n \"Hello Compose\",\n color = MaterialTheme.colorScheme.onSecondary,\n modifier = Modifier.align(Alignment.Center)\n )\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/graphics/ShapesSnippets.kt#L382-L402\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- The `RoundedPolygon` and `RoundedPolygonShape` objects are used to define and apply a hexagonal shape to the image.\n- The code uses [`graphicsLayer`](/reference/kotlin/androidx/compose/ui/graphics/package-summary#(androidx.compose.ui.Modifier).graphicsLayer(kotlin.Function1)) to add an elevation-based shadow to the image. This creates a sense of depth and visual separation from the background.\n- The use of [`remember`](/reference/kotlin/androidx/compose/runtime/package-summary#remember(kotlin.Function0)) blocks optimizes performance by ensuring that the shape and clipping definitions are calculated only once and remembered for later recompositions of the UI.\n\nResults\n-------\n\n**Figure 1.** Custom shape applied as clip.\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\n### Display images\n\nDiscover techniques for using bright, engaging visuals to give your Android app a beautiful look and feel. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/display-images) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]