Created
March 31, 2022 19:33
-
-
Save vishnuharidas/c77582b48c59f10b2cd0d85a44cc3237 to your computer and use it in GitHub Desktop.
Jetpack Compose - Load network image using COIL with custom optional loading and error Composables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.foundation.Image | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.BoxScope | |
import androidx.compose.foundation.layout.Spacer | |
import androidx.compose.foundation.layout.size | |
import androidx.compose.material.CircularProgressIndicator | |
import androidx.compose.material.Icon | |
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.Alignment | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
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.AsyncImagePainter | |
import coil.compose.rememberAsyncImagePainter | |
import coil.request.ImageRequest | |
@Composable | |
fun MyImage( | |
url: String, | |
contentDescription: String?, | |
modifier: Modifier = Modifier, | |
contentScale: ContentScale = ContentScale.Crop, | |
empty: (@Composable BoxScope.() -> Unit)? = null, | |
loading: (@Composable BoxScope.() -> Unit)? = null | |
) { | |
val painter = rememberAsyncImagePainter( | |
model = ImageRequest.Builder(LocalContext.current) | |
.data(url) | |
.crossfade(true) | |
.build() | |
) | |
Box( | |
modifier, | |
contentAlignment = Alignment.Center | |
) { | |
// Actual Image | |
Image( | |
painter = painter, | |
contentDescription = contentDescription, | |
alignment = Alignment.Center, | |
contentScale = contentScale, | |
modifier = Modifier.matchParentSize() | |
) | |
// Placeholder - Progress / Error Icon | |
when (painter.state) { | |
is AsyncImagePainter.State.Error, | |
is AsyncImagePainter.State.Empty -> | |
if (empty != null) { | |
empty() | |
} else Icon( | |
painter = painterResource(id = R.drawable.ic_baseline_broken_image_24), // Add this icon | |
contentDescription = "No Image", | |
tint = Color.Black.copy(alpha = 0.2f) | |
) | |
is AsyncImagePainter.State.Success -> Spacer(Modifier.size(1.dp)) | |
is AsyncImagePainter.State.Loading -> | |
if (loading != null) { | |
loading() | |
} else CircularProgressIndicator( | |
strokeWidth = 1.dp, | |
color = Color.Black.copy(alpha = 0.5f), | |
modifier = Modifier.size(24.dp) | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment