Thracian
Thracian

Reputation: 67149

Jetpack Compose draw on image with Painter

With painter it's possible to draw on ImageBitmap with the snippet

   val imageBitmap: ImageBitmap = imageResource(id = R.drawable.landscape3)

    val customPainter = remember {
        object : Painter() {

            override val intrinsicSize: Size
                get() = Size(imageBitmap.width.toFloat(), imageBitmap.height.toFloat())

            override fun DrawScope.onDraw() {
                drawImage(imageBitmap)
                drawLine(
                    color = Color.Red,
                    start = Offset(0f, 0f),
                    end = Offset(imageBitmap.width.toFloat(), imageBitmap.height.toFloat()),
                    strokeWidth = 5f
                )
            }
        }
    }
    Image(painter = customPainter, contentDescription = null)

loadFontResource is deprecated. Use fontResource instead. imageResource, loadImageResource, vectorResource, and loadVectorResource are deprecated. Use painterResource instead. (I6b809)

with alpha12 imageResource is deprecated. painter's drawImage(imageBitmap) function that draws image has no replacement or another function other than the one takes imageBitmap as parameter?

What's the point of ImageBitmap as of alpha12 since there is no not deprecated function to create it with a resource, and function to get ImageBitmap from Painter does not exist.

Upvotes: 9

Views: 15610

Answers (4)

Ali Najaphi
Ali Najaphi

Reputation: 151

if you need set ImageVector from drawable folder use:

ImageVector.vectorResource(id = R.drawable.ic_example)

ic_example is vector ".xml" file added from svg file

Upvotes: 5

sonique
sonique

Reputation: 4772

with Compose 1.0 stable and above, you should use

useResource("image.png") { loadImageBitmap(it) }

this will return a ImageBitmap object.

There is also painterResource("image.png") but this will return a Painter object.

Upvotes: 3

Spatz
Spatz

Reputation: 20138

starting from Compose UI 1.0.0-beta01

imageResource and vectorResource are now extension functions on ImageBitmap and ImageVector companions respectively. load{Image,Vector,Font}Resource functions have been deleted. (I89130)

import androidx.compose.ui.res.imageResource
// ...
val imageBitmap: ImageBitmap = ImageBitmap.imageResource(R.drawable.landscape3)

painterResource under the hood calls imageFromResource, so we can use it too:

  val imageBitmap: ImageBitmap = imageFromResource(
    LocalContext.current.resources,
    R.drawable.landscape3
  )

Upvotes: 14

郭大鹏
郭大鹏

Reputation: 193

I use this method to use bitmap or SVG

Image(
    painterResource(id = R.drawable.video),
    contentDescription = "",
)

Upvotes: 2

Related Questions