Material icon size adjustment in Jetpack Compose?

Viewed 9949

Jetpack compose provides a nice Icon() object to display icons that accepts a vector asset. Typically, you are able to set the size via a modifier:

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

My problem is I cannot seem to affect the size of the displayed icon when I am using a provided system vector asset (ie, Icons.Filled. or Icons.Default. etc). When I use my own asset, things work as expected. Using the system assets the modifier only increases the UI footprint of the enclosing "box" while the icon stays tiny within:

Sample from IDE Preview

Applying the modifier using 'then' results in the same behavior:

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

Is there something about the native icons? I assumed being vector assets they should be able to resize as well.

5 Answers

With 1.0.x just use the Modifier.size(xx.dp)

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

Internally material icon size is 24.dp

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

And using the size in modifier it's not working, So we can change the icon by copying the icon and change the default height and width.

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.

The accepted answer longer works in 1.0.0-alpha11. This is the associated bug report. As per the bug report comments, the new way of doing this from alpha12 on would be:

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

What works for me is to use Modifier.fillMaxSize(...)), e.g.

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

0.5

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

0.75

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

1.0

To make the answer above more accesible, define some extension functions:

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