Material Jetpack Compose 中的图标大小调整?

Material icon size adjustment in Jetpack Compose?

Jetpack compose 提供了一个很好的 Icon() 对象来显示接受矢量资产的图标。通常,您可以通过修饰符设置大小:

Icon(Icons.Filled.PersonPin, Modifier.preferredSize(64.dp)) 

我的问题是,当我使用提供的系统矢量资源(即Icons.Filled。或Icons.Default.等)。当我使用自己的资产时,一切都按预期进行。使用系统资产,修饰符只会增加封闭“框”的 UI 足迹,而图标在以下范围内保持微小:

使用 'then' 应用修饰符会导致相同的行为:

    Icon(Icons.Filled.PersonPin,Modifier.then(Modifier.preferredSize(128.dp)))

原生图标有什么问题吗?我假设它们是矢量资产,它们也应该能够调整大小。

内部 material 图标大小为 24.dp

// All Material icons (currently) are 24dp by 24dp, with a viewport size of 24 by 24.
@PublishedApi
internal const val MaterialIconDimension = 24f

而且在修改器中使用大小是行不通的,所以我们可以通过复制图标来更改图标并更改默认的高度和宽度。

Icon(Icons.Filled.Person.copy(defaultHeight = 128.dp, defaultWidth = 128.dp))

NOTE: This is not an official recommendation to set the icon size, Just a hack way to change the icon size.

为了让上面的答案更容易理解,定义一些扩展函数:

fun VectorAsset.resize(size: Int) = this.resize(size.dp)
fun VectorAsset.resize(size: Dp) = this.resize(size, size)
fun VectorAsset.resize(width: Int, height: Int) = this.resize(width.dp, height.dp)
fun VectorAsset.resize(width: Dp, height: Dp) =
  this.copy(defaultWidth = width, defaultHeight = height)

已接受的答案在 1.0.0-alpha11 中不再有效。 This 是相关的错误报告。根据错误报告评论,从 alpha12 开始执行此操作的新方法是:

Icon(Icons.Filled.Person, modifier = Modifier.size(128.dp)) 

使用 1.0.x 只需使用 Modifier.size(xx.dp)

Icon(Icons.Filled.Person,
    "contentDescription",
    modifier = Modifier.size(128.dp))

对我有用的是使用Modifier.fillMaxSize(...)),例如

Icon(Icons.Filled.Person, contentDescription = "Person", modifier = Modifier.fillMaxSize(0.5F))

Icon(Icons.Filled.Person, contentDescription = "Person", modifier = Modifier.fillMaxSize(0.75F))

Icon(Icons.Filled.Person, contentDescription = "Person", modifier = Modifier.fillMaxSize(1.0F))