在畫布上顯示分層圖片

您可以混合或重疊來源圖片,在畫布上顯示分層圖片。舉例來說,您可以結合不同的背景和前景可繪項目,複製 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()
)

程式碼的重點

  • 系統會將要合併的圖片分別載入為 ImageBitmap 例項,然後再使用 OverlayImagePainter 合併。
  • 結合的圖片會由 Image 可組合函式算繪,該函式會在算繪時使用自訂繪圖工具來結合來源圖片。

結果

自訂可將兩張圖片互相重疊的 Painter
圖 1Image 使用自訂 Painter,在狗的圖片上重疊半透明的彩虹圖片。

包含此指南的集合

本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:

瞭解如何運用明亮吸睛的視覺元素,為 Android 應用程式打造美觀的視覺效果。

有問題或意見回饋嗎?

請前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。