在画布上显示分层图像

您可以混合或叠加源图像,以便在画布上显示分层图像。例如,您可以通过组合不同的背景和前景 Drawable 来模拟 Android 框架生成应用图标的方式。要显示分层图像,您必须执行以下操作:

  • 在画布上分层图像。
  • 叠加源图像。

版本兼容性

此实现要求您的项目 minSDK 设置为 API 级别 21 或更高。

依赖项

在画布上分层图像

以下代码将两张源图像相互叠加,在画布上渲染合成图像:

class OverlayImagePainter constructor(
    private val image: ImageBitmap,
    private val imageOverlay: ImageBitmap,
    private val srcOffset: IntOffset = IntOffset.Zero,
    private val srcSize: IntSize = IntSize(image.width, image.height),
    private val overlaySize: IntSize = IntSize(imageOverlay.width, imageOverlay.height)
) : Painter() {

    private val size: IntSize = validateSize(srcOffset, srcSize)
    override fun DrawScope.onDraw() {
        // draw the first image without any blend mode
        drawImage(
            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 together
        drawImage(
            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
     */
    override val intrinsicSize: Size get() = size.toSize()

    private fun validateSize(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
        )
        return srcSize
    }
}

代码要点

  • 使用 OverlayImagePainter,这是一个自定义 Painter 实现,您可以使用它将图像叠加到源图像上。混合模式控制图像的组合方式。第一张图像不覆盖任何其他内容,因此不需要混合模式。第二张图像的 Overlay 混合模式会覆盖第二张图像覆盖的第一张图像区域。
  • DrawScope.onDraw() 被重写,并且两张图像在此函数中叠加。
  • 重写了 intrinsicSize,以正确报告合成图像的固有尺寸。

叠加源图像

使用此自定义 Painter,您可以按如下方式将图像叠加到源图像之上:

val rainbowImage = ImageBitmap.imageResource(id = R.drawable.rainbow)
val dogImage = ImageBitmap.imageResource(id = R.drawable.dog)
val customPainter = remember {
    OverlayImagePainter(dogImage, rainbowImage)
}
Image(
    painter = customPainter,
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier.wrapContentSize()
)

代码要点

  • 要组合的图像在通过 OverlayImagePainter 组合之前,都会加载为 ImageBitmap 实例。
  • 合并后的图像由 Image 可组合项渲染,该项在渲染时使用自定义 painter 组合源图像。

结果

Custom Painter that overlays two images on top of each other
图 1:使用自定义 Painter 将半透明彩虹图像叠加在狗的图像上的 Image

包含本指南的集合

本指南是这些精选快速指南集合的一部分,这些集合涵盖了更广泛的 Android 开发目标:

探索使用明亮、引人入胜的视觉效果为您的 Android 应用带来美观外观和感觉的技术。

有问题或反馈?

前往我们的常见问题解答页面,了解快速指南,或联系我们告知您的想法。