How to add Image in Android using Jetpack Compose

I am trying to add Image to the activity using Android Jetpack Compose but it is giving error:

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Image(bitmap = imageFromResource(res = resources, resId =R.drawable.ic_launcher_background))
        }
    }
}


This is the screenshot of Android Studio

Answer

Either of these can be used to get the image resource.

Use the painterResource API to load either vector drawables or rasterized asset formats like PNGs. You don’t need to know the type of the drawable, simply use painterResource.

import androidx.compose.ui.res.painterResource

        Image(painterResource(id = imageResource), contentDescription = contentDescription)

OR

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource

        Image(ImageBitmap.imageResource(id = imageResource), contentDescription = contentDescription)

OR

import androidx.compose.ui.res.vectorResource

        Image(ImageVector.vectorResource(id = imageResource), contentDescription = contentDescription)

Leave a Reply

Your email address will not be published. Required fields are marked *