Home > Net >  How to make initials icons using Coil in Jetpack Compose
How to make initials icons using Coil in Jetpack Compose

Time:01-09

So I am using the Coil library for our image processing and I noticed in the place holder it only takes an int. I want however to display initials if a user does not have an avatar or incase of any error show initials, like this image see below. Problem is, I am new in jetpack compose and not sure how I can achieve this. See my code below.

enter image description here

I have this card that has icon, and some details my Profile Card

ProfileCard( 
    personName = String.format("%s %s", entity.firstName, entity.lastName),
    personC = entity.program ?: "", 
    painter = rememberAsyncImagePainter(model = getProfileAvatar(entity.id)),
    onCardClick = {})

My getProfileAvatar()

private fun getProfileAvatar(id: String) : ImageRequest {
    val url = ServiceAPI.photoUrl(id) 
    return ImageRequest.Builder(requireContext()) 
        .data(url) 
        .addHeader() ) 
        .addHeader("api_key", BuildConfig.API_KEY) 
        .crossfade(true) 
        .build() }

Will appreciate feedback, I did see a couple of post, but don't address the Jetpack part.

CodePudding user response:

You can use coil's SubcomposeAsyncImage for that. It allows you to use any composable function as a placeholder/error state:

SubcomposeAsyncImage(
    model = getProfileAvatar()
) {
    val state = painter.state
    if (state is AsyncImagePainter.State.Loading || state is AsyncImagePainter.State.Error) {
        Text(text = "NG")
    } else {
        SubcomposeAsyncImageContent()
    }
}

CodePudding user response:

Example:

val personName by remember{ mutableStateOf(String.format("%s %s", entity.firstName, entity.lastName)) }
val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
        .allowHardware(false)
        .data("https://xxxx.xxxx.user_avatar.jpg")
        .size(Size.ORIGINAL)
        .build()
)
val isErrorState = painter.state is AsyncImagePainter.State.Error
val textMeasure = rememberTextMeasurer()
val textLayoutResult = textMeasure.measure(text = buildAnnotatedString { append(personName) }, style = TextStyle(color = Color.White, fontSize = 16.sp))

ProfileCard(
    modifier = Modifier.drawBehind {
        if(isErrorState) {
            drawText(textLayoutResult = textLayoutResult)
        }
    },
    personName = personName,
    personC = entity.program ?: "",
    painter = rememberAsyncImagePainter(model = getProfileAvatar(entity.id)),
    onCardClick = {}
)
  • Related