In Jetpack Compose, ImageView
from the traditional Android Views is replaced by the Image
composable. You can use Image
to display images from different sources like resources, drawable, or even URLs using libraries like Coil or Glide.
Basic Example: Displaying a Drawable Resource
@Composable
fun ImageViewExample() {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Sample Image",
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.clip(RoundedCornerShape(16.dp)) // Optional: For rounded corners
.border(2.dp, Color.Gray, RoundedCornerShape(16.dp)) // Optional: Adding a border
)
}
Example: Loading an Image from URL with Coil
Coil is a popular library for image loading in Jetpack Compose.
- Add the Coil dependency to your
build.gradle
file:
implementation "io.coil-kt:coil-compose:2.3.0"
- Use
rememberImagePainter
to load the image:
import coil.compose.rememberAsyncImagePainter
@Composable
fun ImageFromUrlExample() {
Image(
painter = rememberAsyncImagePainter(model = "https://via.placeholder.com/300"),
contentDescription = "Image from URL",
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.clip(RoundedCornerShape(8.dp)) // Rounded corners
.border(2.dp, Color.Blue, RoundedCornerShape(8.dp))
)
}
Example: Scaling and Alignment
You can control how the image fits within its bounds using contentScale
and alignment options.
@Composable
fun ScaledImageExample() {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Scaled Image",
contentScale = ContentScale.Crop, // Options: FillBounds, Fit, Inside, etc.
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
}
Example: Image with Background and Overlay
@Composable
fun ImageWithBackgroundExample() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.background(Color.LightGray),
contentAlignment = Alignment.Center // Align the image within the box
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Image with Background",
contentScale = ContentScale.Cover
)
}
}
Advanced: Animated Image with Coil
You can enable animations for loading images using Coil.
@Composable
fun AnimatedImageFromUrl() {
Image(
painter = rememberAsyncImagePainter(
model = "https://via.placeholder.com/300",
placeholder = painterResource(id = R.drawable.placeholder), // Optional: Placeholder
error = painterResource(id = R.drawable.error_image) // Optional: Error fallback
),
contentDescription = "Animated Image",
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
}
Key Properties of Image
:
painter
: Source of the image (e.g.,painterResource
or Coil’srememberAsyncImagePainter
).contentDescription
: Accessibility description for the image.contentScale
: Controls how the image scales (e.g.,Crop
,Fit
,FillBounds
).modifier
: Apply customizations like size, padding, border, clipping, etc.
Let me know if you’d like more specific examples or use cases! š