Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Vous pouvez mélanger ou superposer des images sources pour afficher des images superposées sur un canevas.
Par exemple, vous pouvez reproduire la façon dont le framework Android génère des icônes d'application en combinant des drawables d'arrière-plan et de premier plan distincts. Pour afficher des images superposées, procédez comme suit:
Empilez des images sur un canevas.
Superposez la source.
Compatibilité des versions
Cette implémentation nécessite que la version minimale du SDK de votre projet soit définie sur le niveau d'API 21 ou supérieur.
Dépendances
Empilez des images sur un canevas
Le code suivant superpose deux images sources, ce qui génère une image mélangée sur le canevas:
classOverlayImagePainterconstructor(privatevalimage:ImageBitmap,privatevalimageOverlay:ImageBitmap,privatevalsrcOffset:IntOffset=IntOffset.Zero,privatevalsrcSize:IntSize=IntSize(image.width,image.height),privatevaloverlaySize:IntSize=IntSize(imageOverlay.width,imageOverlay.height)):Painter(){privatevalsize:IntSize=validateSize(srcOffset,srcSize)overridefunDrawScope.onDraw(){// draw the first image without any blend modedrawImage(image,srcOffset,srcSize,dstSize=IntSize(this@onDraw.size.width.roundToInt(),this@onDraw.size.height.roundToInt()))// draw the second image with an Overlay blend mode to blend the two togetherdrawImage(imageOverlay,srcOffset,overlaySize,dstSize=IntSize(this@onDraw.size.width.roundToInt(),this@onDraw.size.height.roundToInt()),blendMode=BlendMode.Overlay)}/** * Return the dimension of the underlying [ImageBitmap] as it's intrinsic width and height */overridevalintrinsicSize:Sizeget()=size.toSize()privatefunvalidateSize(srcOffset:IntOffset,srcSize:IntSize):IntSize{require(srcOffset.x>=0&&
srcOffset.y>=0&&
srcSize.width>=0&&
srcSize.height>=0&&
srcSize.width<=image.width&&
srcSize.height<=image.height)returnsrcSize}}
Utilise OverlayImagePainter, qui est une implémentation personnalisée de Painter que vous pouvez utiliser pour superposer des images à l'image source. Le mode de fusion contrôle la façon dont les images sont combinées. La première image ne remplace rien d'autre. Aucun mode de fusion n'est donc nécessaire. Le mode de fusion Overlay de la deuxième image écrase les zones de la première image qui sont recouvertes par la deuxième image.
DrawScope.onDraw() est ignoré et les deux images sont superposées dans cette fonction.
intrinsicSize est remplacé pour indiquer correctement la taille intrinsèque de l'image combinée.
Superposer l'image source
Avec ce peintre personnalisé Painter, vous pouvez superposer une image sur l'image source comme suit:
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/02/06 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/02/06 (UTC)."],[],[],null,["# Display layered images on a canvas\n\n\u003cbr /\u003e\n\nYou can blend or overlay source images to display layered images on a canvas.\nFor example, you can replicate how the Android Framework generates app icons by\ncombining separate background and foreground drawables. To display layered\nimages, you must do the following:\n\n- Layer images on a canvas.\n- Overlay the source.\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 \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 \n```\n\n\u003cbr /\u003e\n\nLayer images on a canvas\n------------------------\n\nThe following code layers two source images on top of each other, rendering a\nblended image on the canvas:\n\n\n```kotlin\nclass OverlayImagePainter constructor(\n private val image: ImageBitmap,\n private val imageOverlay: ImageBitmap,\n private val srcOffset: IntOffset = IntOffset.Zero,\n private val srcSize: IntSize = IntSize(image.width, image.height),\n private val overlaySize: IntSize = IntSize(imageOverlay.width, imageOverlay.height)\n) : Painter() {\n\n private val size: IntSize = validateSize(srcOffset, srcSize)\n override fun DrawScope.onDraw() {\n // draw the first image without any blend mode\n drawImage(\n image,\n srcOffset,\n srcSize,\n dstSize = IntSize(\n this@onDraw.size.width.roundToInt(),\n this@onDraw.size.height.roundToInt()\n )\n )\n // draw the second image with an Overlay blend mode to blend the two together\n drawImage(\n imageOverlay,\n srcOffset,\n overlaySize,\n dstSize = IntSize(\n this@onDraw.size.width.roundToInt(),\n this@onDraw.size.height.roundToInt()\n ),\n blendMode = BlendMode.Overlay\n )\n }\n\n /**\n * Return the dimension of the underlying [ImageBitmap] as it's intrinsic width and height\n */\n override val intrinsicSize: Size get() = size.toSize()\n\n private fun validateSize(srcOffset: IntOffset, srcSize: IntSize): IntSize {\n require(\n srcOffset.x \u003e= 0 &&\n srcOffset.y \u003e= 0 &&\n srcSize.width \u003e= 0 &&\n srcSize.height \u003e= 0 &&\n srcSize.width \u003c= image.width &&\n srcSize.height \u003c= image.height\n )\n return srcSize\n }\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/images/CustomPainterSnippets.kt#L79-L128\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- Uses `OverlayImagePainter`, which is a custom [`Painter`](/reference/kotlin/androidx/compose/ui/graphics/painter/Painter) implementation that you can use to overlay images over the source image. The blend mode controls how the images are combined. The first image is not overwriting anything else, so no blend mode is needed. The `Overlay` blend mode of the second image overwrites the areas of the first image that are covered by the second image.\n- `DrawScope.onDraw()` is overridden and the two images are overlaid in this function.\n- `intrinsicSize` is overridden to correctly report the intrinsic size of the combined image.\n\nOverlay source image\n--------------------\n\nWith this custom painter `Painter`, you can overlay an image on top of the\nsource image as follows:\n\n\n```kotlin\nval rainbowImage = ImageBitmap.imageResource(id = R.drawable.rainbow)\nval dogImage = ImageBitmap.imageResource(id = R.drawable.dog)\nval customPainter = remember {\n OverlayImagePainter(dogImage, rainbowImage)\n}\nImage(\n painter = customPainter,\n contentDescription = stringResource(id = R.string.dog_content_description),\n contentScale = ContentScale.Crop,\n modifier = Modifier.wrapContentSize()\n)https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/images/CustomPainterSnippets.kt#L64-L74\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- The images to be combined are each loaded as [`ImageBitmap`](/reference/kotlin/androidx/compose/ui/graphics/ImageBitmap) instances before being combined using `OverlayImagePainter`.\n- The combined images are rendered by an [`Image`](/reference/kotlin/androidx/compose/foundation/package-summary#Image(androidx.compose.ui.graphics.ImageBitmap,kotlin.String,androidx.compose.ui.Modifier,androidx.compose.ui.Alignment,androidx.compose.ui.layout.ContentScale,kotlin.Float,androidx.compose.ui.graphics.ColorFilter,androidx.compose.ui.graphics.FilterQuality)) composable that uses the custom painter to combine the source images when rendering.\n\nResults\n-------\n\n**Figure 1** : An `Image` that uses a custom `Painter` to overlay a semi-transparent rainbow image over the image of a dog.\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)"]]