Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Image from drawable in Jetpack compose?

I have tried below code but it reflects nothing in the UI, I'm missing anything here?

class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContent {             loadUi()         }     }      @Composable     fun loadUi() {         CraneWrapper {             MaterialTheme {                 Image(                     (ResourcesCompat.getDrawable(                         resources,                         R.mipmap.ic_launcher,                         null                     ) as BitmapDrawable).bitmap                 )             }         }     } } 
like image 873
Malik Motani Avatar asked Jun 26 '19 07:06

Malik Motani


People also ask

Which function is used is to load a drawable image resource?

getDrawable(res, R. drawable. my_image, null);

How do I add an image to a drawable XML file?

Step 1: In this method first of all in your system find your required images and copy the image as we do normally. Step 2: Then open the Android Studio go to the app > res > drawable > right-click > Paste as shown in the below figure. Step 3: Then a pop-up screen will arise like below.


2 Answers

You can use the painterResource function:

 Image(painterResource(R.drawable.ic_xxxx),"content description") 

The resources with the given id must point to either fully rasterized images (ex. PNG or JPG files) or VectorDrawable xml assets.
It means that this method can load either an instance of BitmapPainter or VectorPainter for ImageBitmap based assets or vector based assets respectively.

Example:

Card(     modifier = Modifier.size(48.dp).tag("circle"),     shape = CircleShape,     elevation = 2.dp ) {     Image(         painterResource(R.drawable.ic_xxxx),         contentDescription = "",         contentScale = ContentScale.Crop,         modifier = Modifier.fillMaxSize()     ) } 

enter image description here

like image 122
Gabriele Mariotti Avatar answered Sep 20 '22 21:09

Gabriele Mariotti


Starting at version 1.0.0-beta01:

Image(     painter = painterResource(R.drawable.your_drawable),     contentDescription = "Content description for visually impaired" ) 
like image 34
Cristan Avatar answered Sep 19 '22 21:09

Cristan