如何在 Jetpack Compose 中填充矢量图像的背景?

Kri*_*lsh 2 android android-vectordrawable android-jetpack-compose

我有一个矢量图像,我想将其放在按钮上。不幸的是,我的图像显示为白色背景。如何用按钮的颜色填充背景?

带箭头的按钮

这是按钮的代码。

@Composable
fun UserEducationPrimaryButton(
primaryButtonText: String,
primaryButtonClick: (() -> Unit)?,
showButtonArrow: Boolean
) {
val displayUtils = get<DisplayUtils>()
val configuration = LocalConfiguration.current
val screenWidth = displayUtils.convertDpToPixels(configuration.screenWidthDp * 1.0f)
val dpSize = DpSize(width = Dp(screenWidth.toFloat()), height = 52.dp)
// Use the state to change our UI
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val color = if (!isPressed) MaterialTheme.colors.secondary else Color.LightGray
val paddingValues = PaddingValues(horizontal = 32.dp, vertical = 10.dp)

//primary button
Button(
    onClick = primaryButtonClick ?: {},
    modifier = Modifier
        .fillMaxWidth()
        .padding(horizontal = 24.dp)
        .size(dpSize),
    shape = RoundedCornerShape(ROUNDED_CORNER_SHAPE_BUTTON),
    interactionSource = interactionSource,
    colors = ButtonDefaults.buttonColors(backgroundColor = color),
    contentPadding = paddingValues
) {
    Text(
        modifier = Modifier,
        textAlign = TextAlign.Center,
        text = primaryButtonText,
        style = TextStyle(
            color = MaterialTheme.colors.onPrimary,
            fontWeight = FontWeight.Bold,
            fontSize = 17.sp
        )
    )
    if (showButtonArrow) {
        Spacer(modifier = Modifier.width(16.dp))
        Surface (modifier = Modifier.fillMaxSize(),
        color = color){
            Image(
                painter = rememberImagePainter(
                    ImageRequest.Builder(LocalContext.current)
                        .data(R.drawable.ic_user_education_arrow)
                        .build()
                ),
                contentScale = ContentScale.Fit,
                contentDescription = null,
                modifier = Modifier,
                colorFilter = ColorFilter.tint(
                    MaterialTheme.colors.onSecondary,
                    BlendMode.ColorBurn
                ),
            )
        }

    }
}
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*tti 5

您可以使用Modifier.background.

就像是:

Icon(
    painterResource(id = R.drawable.ic_xxxxx),
    contentDescription = "content description",
    modifier = Modifier.background(MaterialTheme.colors.primary),
    tint = White
)
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢Image

Image(
    painter = rememberAsyncImagePainter(
        ImageRequest.Builder(LocalContext.current)
            .data(R.drawable.ic_xxxxx)
            .build()
    ),
    contentScale = ContentScale.Fit,
    contentDescription = "content description",
    modifier = Modifier.background(MaterialTheme.colors.primary)
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述