Android & Kotlin

Working with Jetpack Compose Image in Android

Pinterest LinkedIn Tumblr

Want to learn how to use Jetpack Compose Image in Android? In this tutorial, we’ll look at how we can display some images on Jetpack Compose UI.

Types of ways of display images in Jetpack Compose

So have various types of images that we can display, so let’s have a look what are the possible option

  1. Bundled images
  2. Vector images
  3. Online image resources

Display Bundled images on compose UI

Now bundled images are images that are stored inside our app and can be accessed without an internet connection. So that what we called bundle images.

To add a bundled image to your app, first add the image file to your project’s resources drawable folder.

package com.compose.workingwithimages

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

@Composable
fun ImageCompose() {
  Column(horizontalAlignment = Alignment.CenterHorizontally) {
    Row(
      modifier = Modifier
        .fillMaxWidth(1f)
        .height(120.dp),
      horizontalArrangement = Arrangement.Center
    ) {
      val imgRes = painterResource(id = R.drawable.india_gate)
      Image(
        painter = imgRes,
        contentDescription = null,
        modifier = Modifier.fillMaxWidth(),
        contentScale = ContentScale.FillWidth
      )
    }
  }
}

Let call the composable function in MainActivity and run the app then we should see now the image is appearing on the screen. Just this snapshot.

You can also customize the image using the available parameters, such as width, height, and content scale.

ContentScale

contentScale parameter have multiple option based in need you can used that, eg.

  • None – Do not apply any scaling to the source
  • FillBounds – Scale horizontal and vertically non-uniformly to fill the destination bounds.
  • Crop – Scale the source uniformly (maintaining the source’s aspect ratio) so that both dimensions (width and height) of the source will be equal to or larger than the corresponding dimension of the destination.
  • Inside – Scale the source to maintain the aspect ratio to be inside the destination bounds if the source is larger than the destination
  • Fit  – Scale the source uniformly (maintaining the source’s aspect ratio) so that both dimensions (width and height) of the source will be equal to or less than the corresponding dimension of the destination
  • FillHeight – Scale the source maintaining the aspect ratio so that the bounds match the destination height. 
  • FillWidth – Scale the source maintaining the aspect ratio so that the bounds match the destination width.
      val imgRes = painterResource(id = R.drawable.india_gate)
      Image(painter = imgRes, contentDescription = null, contentScale = ContentScale.FillWidth)

Load Vector image jetpack compose

Vector Images are slightly different, however they are also bundled images. and displaying also very similar. The reason why I’ve added them separately here is because of the way we create them. It is allowed a lot of flexibility Icon and small images in the application. We will see how we can add them. In android studio select resource => Vector Asset => choose assets and click on OK. The same image I wanna display like this

  val iconRes = painterResource(id = R.drawable.ic_celebration)
    Image(painter = iconRes, contentDescription = null, colorFilter = ColorFilter.tint(Color.Blue))    

colorFilter

Using that you can apply color filter on vector image.

Jetpack compose image from Url

Jetpack Compose Image allows you to load images from URLs. That is stored somewhere on server, our app downloads them and shows them to the user. This is very useful because instead of bundling images inside our application and taking up a lot of space we simply have them on a server and access them when it needed.

To load an image from a URL, use the Coil library, which is a popular image-loading library for Android. First, add the Coil dependency to your project.

    implementation "io.coil-kt:coil-compose:2.2.2"

After adding Coil dependency you have to add Internet uses permission, because we are going to load image from server.

  <uses-permission android:name="android.permission.INTERNET"/> 
    AsyncImage(
      model = "http://androidwave.com/wp-content/uploads/2023/03/staggered-grid-layout-android-kotlin.png",
      contentDescription = null
    )  

Customize the image with modifiers.

Jetpack Compose Image allows you to customize the image using modifiers. For example, you can use the size modifier to set the size of the image, the clip modifier to clip the image to a specific shape, and the border modifier to add a border around the image. For example, let’s see this Ultimate Guide to Jetpack Compose List

    AsyncImage(
      model = "http://androidwave.com/wp-content/uploads/2023/03/staggered-grid-layout-android-kotlin.png",
      modifier = Modifier
        .size(200.dp)
        .border(
          width = 1.dp, color = Color.LightGray, shape = CircleShape
        )
        .padding(3.dp)
        .clip(CircleShape),
      contentScale = ContentScale.Crop,
      contentDescription = null
    )

You can also use the alpha modifier to adjust the transparency of the image, the rotation modifier to rotate the image, and the scale modifier to scale the image. With these modifiers, you can create unique and visually appealing images in your Android app.

Handle errors and loading states.

When working with images in your Android app using Jetpack Compose Image, it’s important to handle errors and loading states. You can use the error and loading parameters to display a placeholder image or message when the image fails to load or is still loading. This ensures a better user experience and prevents frustration when images don’t load properly. Additionally, you can use the contentScale parameter to adjust the scaling of the image to fit the available space.

    AsyncImage(
      model = ImageRequest.Builder(LocalContext.current)
        .data("https://androidwave.com/wp-content/uploads/2023/03/ultimate-guide-to-jetpack-compose-list.png")
        .crossfade(true)
        .build(),
      placeholder = painterResource(R.drawable.ic_baseline_image_24),
      contentDescription = null,
      contentScale = ContentScale.Crop,
//      modifier = Modifier.clip(CircleShape)
    )

Finally, Let’s find out examples of Image Compose

package com.compose.workingwithimages

import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest

@Composable
fun ImageCompose() {
  Column(horizontalAlignment = Alignment.CenterHorizontally) {
    Row(
      modifier = Modifier
        .fillMaxWidth(1f)
        .height(200.dp),
      horizontalArrangement = Arrangement.Center
    ) {
      val imgRes = painterResource(id = R.drawable.india_gate)
      Image(
        painter = imgRes,
        contentDescription = null,
        modifier = Modifier.fillMaxWidth(),
        contentScale = ContentScale.FillWidth
      )
    }
    Spacer(modifier = Modifier.height(8.dp))
    val iconRes = painterResource(id = R.drawable.ic_celebration)
    Image(painter = iconRes, contentDescription = null, colorFilter = ColorFilter.tint(Color.Blue))

    Spacer(modifier = Modifier.height(8.dp))

    AsyncImage(
      model = "https://androidwave.com/wp-content/uploads/2023/03/staggered-grid-layout-android-kotlin.png",
      modifier = Modifier
        .size(150.dp)
        .border(
          width = 1.dp, color = Color.LightGray, shape = CircleShape
        )
        .padding(3.dp)
        .clip(CircleShape),
      contentScale = ContentScale.Crop,
      contentDescription = null
    )
    
    AsyncImage(
      model = ImageRequest.Builder(LocalContext.current)
        .data("https://androidwave.com/wp-content/uploads/2023/03/ultimate-guide-to-jetpack-compose-list.png")
        .crossfade(true).build(),
      placeholder = painterResource(R.drawable.ic_baseline_image_24),
      contentDescription = null,
      contentScale = ContentScale.Crop,
//      modifier = Modifier.clip(CircleShape)
    )
  }
}

Conclusion

That’s all about Images in Jetpack Compose, In this jetpack compose tutorial we learned about different ways of displaying images, such as bundle images, vector images, and load from the internet. I hope this post will help you. If you have any questions please reach out to the comment box.

Write A Comment