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))
}
}
}
mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. interface MutableState<T> : State<T> { override var value: T. } Any changes to value will schedule recomposition of any composable functions that read value .
Build better apps faster with. Jetpack Compose. Jetpack Compose is Android's modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.
most of the cases for local image loading can be done using painterResource in Image
for example:
Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "")
or if you are interested in changing the color of the image asset, then use Icon with painterResource
Icon(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "", tint = Color.Red)
or if you want to load from Remote URL then use Coil
add dependency:
implementation "dev.chrisbanes.accompanist:accompanist-coil:0.6.1"
and then use it like below:
CoilImage(
data = "https://www.instaily.com/images/android.jpg",
contentDescription = "android",
alignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(.60f),
contentScale = ContentScale.Crop,
loading = {
Box(
modifier = Modifier.background(
shape = RoundedCornerShape(20.dp),
color = Teal200
)
)
},
error = {
Box(
modifier = Modifier.background(
shape = RoundedCornerShape(20.dp),
color = Teal200
)
)
}
)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With