简体   繁体   中英

How can I create a coloured Icon from a vector drawable resource in Jetpack Compose?

I want to implement a Sign In With Google button in Jetpack Compose. I downloadedthis SVG and added a white background in Inkscape so it would be usable in both the recommended styles (white or blue button background), then imported it into resources.

This is how it looks in the text editor:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:fillColor="#ffffff"
      android:pathData="M0,0h24v24h-24z"
      android:strokeWidth="0"
      android:strokeColor="#00000000"/>
  <path
      android:fillColor="#4285f4"
      android:pathData="m22.766,12.248c0,-0.724 -0.064,-1.412 -0.174,-2.081l-10.358,0l0,4.134l5.931,0c-0.266,1.357 -1.045,2.503 -2.2,3.282l0,2.75l3.538,0c2.072,-1.916 3.263,-4.739 3.263,-8.085z"
  />
  <path
      android:fillColor="#34a853"
      android:pathData="m12.234,23c2.97,0 5.454,-0.99 7.269,-2.668l-3.538,-2.75c-0.99,0.66 -2.246,1.063 -3.731,1.063 -2.869,0 -5.298,-1.934 -6.169,-4.547l-3.648,0l0,2.832c1.806,3.593 5.518,6.068 9.818,6.068z"
  />
  <path
      android:fillColor="#fbbc05"
      android:pathData="m6.065,14.099c-0.229,-0.66 -0.348,-1.366 -0.348,-2.099 0,-0.733 0.128,-1.439 0.348,-2.099l0,-2.832l-3.648,0c-0.752,1.485 -1.183,3.153 -1.183,4.932 0,1.778 0.431,3.447 1.183,4.932z"
  />
  <path
      android:fillColor="#ea4335"
      android:pathData="m12.234,5.354c1.623,0 3.071,0.559 4.217,1.65l3.135,-3.135c-1.898,-1.778 -4.382,-2.869 -7.352,-2.869 -4.299,0 -8.012,2.475 -9.818,6.068l3.648,2.832c0.871,-2.612 3.3,-4.547 6.169,-4.547z"
  />
</vector>

I used it in a Button like this:

Button(onClick = { /*TODO*/ },) {
    Icon(painter = painterResource(id = R.drawable.ic_google_logo_filled),
        "Google logo")
    Text("Sign In With Google",
    modifier = Modifier.padding(start = 8.dp))
}

It renders in colour in Android Studio, but in previews and the emulator it ignores all the fillColor and strokeColor attributes and renders it white. If I remove the background from the XML I can see the G shape, as long as the button doesn't have a white background. If I restore the background but change its fillColor to something else it stays white.

The Icon applies the default tint LocalContentColor.current.copy(alpha = LocalContentAlpha.current)

Use tint= Color.Unspecified to avoid it:

Icon(
    painter = painterResource(id = R.drawable.xxxx),
    "Google logo",
    tint= Color.Unspecified
)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM