我怎样在Jetpack Compose中从矢量可绘资源创建一个有颜色的图标?

10

我想在Jetpack Compose中实现“使用Google登录”按钮。我下载了这个SVG文件,并在Inkscape中添加了白色背景,以便在推荐的两种样式(白色或蓝色按钮背景)中都可用,然后将其导入到资源中。

以下是它在文本编辑器中的外观:

<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>

我在按钮中使用它:

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))
}

在Android Studio中,它会以彩色呈现,但在预览和模拟器中,它会忽略所有的fillColor和strokeColor属性,并将其渲染成白色。如果我从XML中删除背景,我可以看到G形状,只要按钮没有白色背景。但如果我恢复背景,但更改其fillColor为其他颜色,则它仍然是白色。

1个回答

18
< p > Icon 应用默认的色调 LocalContentColor.current.copy(alpha = LocalContentAlpha.current)。< /p> < p > 使用 tint= Color.Unspecified 可以避免这种情况:< /p>
Icon(
    painter = painterResource(id = R.drawable.xxxx),
    "Google logo",
    tint= Color.Unspecified
)

enter image description here


1
谢谢,那个可行。我也发现使用Image而不是Icon可以工作,但我想从语义上讲Icon更正确吧? - realh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接