在 Compose 中,Painter
物件用於代表可繪製的內容
(取代 Android 中定義的 Drawable
API) 和影響
測量及版面配置。A 罩杯
BitmapPainter
會採用可在畫面上繪製 Bitmap
的 ImageBitmap
。
在多數用途中,使用上述的 painterResource()
會傳回正確的
素材資源的繪圖工具 (例如 BitmapPainter
或 VectorPainter
)。如要
進一步瞭解這兩者的差異 - 請參閱 ImageBitmap 與 ImageVector 一節。
Painter
與 DrawModifier
不同,後者只會在
邊界 (無影響) 的測量或版面配置
可組合函式。
如要建立自訂繪圖工具,請擴充 Painter
類別,然後實作
onDraw
方法,可供存取 DrawScope
繪製自訂項目
圖像。您也可以覆寫 intrinsicSize
,以便用於
影響該元件包含的可組合函式:
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 } }
現在我們已建立自訂 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() )
結合兩張圖片與自訂繪圖工具的輸出內容如下所示:
![自訂可將兩張圖片互相重疊的 Painter](https://developer.android.com/static/develop/ui/compose/images/graphics-rainbowoverlay.jpg?authuser=0000&hl=zh-tw)
自訂繪圖工具也可以與 Modifier.paint(customPainter)
搭配使用
將內容繪製到可組合項中,如下所示:
val rainbowImage = ImageBitmap.imageResource(id = R.drawable.rainbow) val dogImage = ImageBitmap.imageResource(id = R.drawable.dog) val customPainter = remember { OverlayImagePainter(dogImage, rainbowImage) } Box( modifier = Modifier.background(color = Color.Gray) .padding(30.dp) .background(color = Color.Yellow) .paint(customPainter) ) { /** intentionally empty **/ }
為您推薦
- 注意:系統會在 JavaScript 關閉時顯示連結文字
- ImageBitmap 與 ImageVector {:#bitmap-vs-vector}
- Compose 中的圖形
- 載入圖片 {:#loading-images}