Skip to content

Instantly share code, notes, and snippets.

@opatry

opatry/GridLayer.kt

Created Mar 18, 2021
Embed
What would you like to do?
A Jetpack Compose grid overlay to ease alignment of design mockup
// Copyright (c) 2021 Olivier Patry
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package net.opatry.ui.util
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun GridLayer(gridSize: Dp = 8.dp, color: Color = Color.Red.copy(alpha = .3f)) {
Canvas(Modifier.fillMaxSize()) {
val offset = gridSize.toPx()
val lineWidth = 1f
var x = 0f
while (x < size.width) {
drawLine(
start = Offset(x, 0f),
end = Offset(x, size.height),
strokeWidth = lineWidth,
color = color,
)
x += offset
}
var y = 0f
while (y < size.height) {
drawLine(
start = Offset(0f, y),
end = Offset(size.width, y),
strokeWidth = lineWidth,
color = color,
)
y += offset
}
}
}
@opatry

This comment has been minimized.

Copy link
Owner Author

@opatry opatry commented Mar 18, 2021

Example of use:

Column {
    Text("Example of text", Modifier.padding(8.dp))
    Button({}, Modifier.padding(16.dp)) {
        Text("And a button")
    }
}

val showGrid = booleanResource(R.bool.debug_show_grid)
if (showGrid) {
  GridLayer()
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment