'Set Drawable instance to Image in Jetpack Compose
In Jetpack Compose, who can tell me is there a way to assign a Drawable Object to the Image compose view?
I took the apps installed on an Android device. I get an icon with the type that is Drawable and I want to use it in Image
val icon: Drawable = packageInfor.applicationInfo.loadIcon(packageManager)
I found there are 3 functions that can assign images
- From Painter (IdRes)
- From ImageBitmap
- From ImageVector
From all that I don't know how to assign a Drawable instance.
Solution 1:[1]
After all, I found a simple solution with Accompanist. Thanks to @Sinner of the System for suggesting to me.
Adding this dependency to the app gradle.
implementation "com.google.accompanist:accompanist-drawablepainter:<version>" //0.16.0
Using:
Image(
painter = rememberDrawablePainter(drawable = drawable),
contentDescription = "content description",
)
Check out: Drawable PainterĀ¶
Solution 2:[2]
Edit: You should definitely use the accompanist library as recommended in the Wilson Tran answer. Since it provides support for several kinds of drawables.
If you're not using the accompanist library, you can do the following...
ContextCompat.getDrawable(LocalContext.current, R.mipmap.ic_launcher)?.let {
Image(bitmap = it.toBitmap().asImageBitmap(), contentDescription = null)
}
You can set the drawable size in toBitmap
function if you want...
Solution 3:[3]
If you're using the Coil library, rememberImagePainter
will accept an Any?
as its data argument, which includes support for Drawable
instances. I'm using this as an all-in-one solution for my images rather than importing Accompanist.
Image(
painter = rememberImagePainter(data = myDrawableInstance)
)
Solution 4:[4]
You can do like that
val backgroundImage = painterResource(R.drawable.your_image)
and then pass this to your image like that
Image(painter = backgroundImage, contentDescription = null)
That will work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wilson Tran |
Solution 2 | |
Solution 3 | lase |
Solution 4 | Rajshekhar |