Skip to content

HexGrid

gonodono edited this page Jun 29, 2024 · 2 revisions

Package: com.gonodono.hexgrid.compose

The library's Composable version is named HexGrid, and it has all of the same features and functionalities as the View version, except that its Grid is cannot be modified through child layout declarations.

The following example shows all of HexGrids custom parameters, most with their default values, and onGridTap assigned a simple function to demonstrate updating an ImmutableGrid.

var grid by remember {
    mutableStateOf(ImmutableGrid(3, 3, insetEvenLines = true))
}
HexGrid(
    grid = grid,
    fitMode = FitMode.FitColumns,
    crossMode = CrossMode.AlignCenter,
    hexOrientation = HexOrientation.Horizontal,
    strokeWidth = Dp.Hairline,
    colors = HexGridDefaults.colors(),
    indicesShown = HexGridDefaults.indicesShown(),
    onGridTap = { address -> grid = grid.toggled(address) },
    onOutsideTap = {}
) { address ->
    Surface(
        color = Color.Cyan,
        shadowElevation = 4.dp,
        shape = getHexShape(inset = 5.dp),
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painter = painterResource(id = R.drawable.example),
            contentDescription = "Icon",
            alignment = Alignment.Center,
            colorFilter = when {
                grid[address].isSelected -> ColorFilter.tint(Color.Red)
                else -> null
            }
        )
    }
}

As you can see above, Compose's Grid implementation is ImmutableGrid, which is a wrapper around MutableGrid that hides the set operators, and is marked @Immutable. In onGridTap(), the selected state is toggled by copying the existing ImmutableGrid and replacing the Grid.State at the given address with one that has the opposite state. The toggled() extension function is a convenience to handle the copy/replace, and we set its return as the new grid.

The copy() functions in Grid are meant mainly for this usage, though they're available for MutableGrid too, obviously. They have similar semantics to a data class's copy() function, in that you pass only the changes that you need applied. The function used above is for a single change, and there's also an overload that takes a Map<Grid.Address, Grid.State> to apply multiple changes at once.

The last thing to note here is the getHexShape() function that is defined in HexGridItemScope, the block where the (optional) cell items are created. This provides similar functionality to HexGridView's HexDrawable background for its child items, though it's up to the user here to apply the Shape wherever is appropriate.


Next: Notes →

Clone this wiki locally