Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Você pode mesclar ou sobrepor imagens de origem para mostrar imagens em camadas em uma tela.
Por exemplo, é possível replicar como o Android Framework gera ícones de apps
combinando drawables de segundo e primeiro planos separados. Para mostrar imagens
em camadas, faça o seguinte:
Sobrepor imagens em uma tela.
Sobreponha a fonte.
Compatibilidade de versões
Essa implementação exige que o minSDK do projeto seja definido como nível 21 da API ou
mais recente.
Dependências
Sobrepor imagens em uma tela
O código a seguir sobrepõe duas imagens de origem, renderizando uma
imagem mesclada na tela:
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}}
Usa OverlayImagePainter, que é uma implementação personalizada de Painter
que pode ser usada para sobrepor imagens à imagem de origem. O modo de mesclagem
controla como as imagens são combinadas. A primeira imagem não está substituindo
nada, então nenhum modo de mesclagem é necessário. O modo de mesclagem Overlay da
segunda imagem substitui as áreas da primeira imagem que são cobertas pela
segunda imagem.
DrawScope.onDraw() é substituído, e as duas imagens são sobrepostas nessa
função.
intrinsicSize é substituído para informar corretamente o tamanho intrínseco da
imagem combinada.
Imagem de origem da sobreposição
Com esse Painter personalizado, é possível sobrepor uma imagem à
imagem de origem da seguinte maneira:
As imagens a serem combinadas são carregadas como instâncias ImageBitmap
antes de serem combinadas usando OverlayImagePainter.
As imagens combinadas são renderizadas por um elemento combinável Image que usa o
pintor personalizado para combinar as imagens de origem durante a renderização.
Resultados
Figura 1: um Image que usa um Painter personalizado para sobrepor uma imagem semitransparente de arco-íris à imagem de um cachorro.
Coleções que contêm este guia
Este guia faz parte destas coleções selecionadas de guias rápidos que abrangem
metas mais amplas de desenvolvimento para Android:
Exibir imagens
Descubra técnicas para usar recursos visuais vibrantes e envolventes e
dar ao seu app Android uma aparência bonita.
O conteúdo e os exemplos de código nesta página estão sujeitos às licenças descritas na Licença de conteúdo. Java e OpenJDK são marcas registradas da Oracle e/ou suas afiliadas.
Última atualização 2025-02-06 UTC.
[null,null,["Última atualização 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)"]]