diff --git a/orx-shapes/src/demo/kotlin/DemoRectangleGrid.kt b/orx-shapes/src/demo/kotlin/DemoRectangleGrid.kt new file mode 100644 index 00000000..46d4b617 --- /dev/null +++ b/orx-shapes/src/demo/kotlin/DemoRectangleGrid.kt @@ -0,0 +1,29 @@ +import org.openrndr.application +import org.openrndr.color.ColorRGBa +import org.openrndr.extensions.SingleScreenshot +import org.openrndr.extra.shapes.grid + +fun main() { + application { + configure { + width = 800 + height = 800 + } + program { + if (System.getProperty("takeScreenshot") == "true") { + extend(SingleScreenshot()) { + this.outputFile = System.getProperty("screenshotPath") + } + } + extend { + drawer.fill = ColorRGBa.WHITE.opacify(0.25) + drawer.stroke = ColorRGBa.PINK + val grid = drawer.bounds.grid(8, 4, 20.0, 20.0, -20.0, -20.0) + for (cell in grid.flatten()) { + drawer.rectangle(cell) + drawer.lineSegment(cell.position(0.0, 0.0), cell.position(1.0, 1.0)) + } + } + } + } +} \ No newline at end of file diff --git a/orx-shapes/src/main/kotlin/RectangleGrid.kt b/orx-shapes/src/main/kotlin/RectangleGrid.kt new file mode 100644 index 00000000..b9eef519 --- /dev/null +++ b/orx-shapes/src/main/kotlin/RectangleGrid.kt @@ -0,0 +1,43 @@ +package org.openrndr.extra.shapes + +import org.openrndr.shape.Rectangle + +/** + * Splits [Rectangle] into a grid of [Rectangle]s + * @param columns the number of columns in the resulting grid + * @param rows the number of rows in the resulting grid + * @param marginX the unitless margin width + * @param marginY the unitless margin height + * @param gutterX the unitless gutter width, the horizontal space between grid cells + * @param gutterY the unitless gutter height, the vertical space between grid cells + */ +fun Rectangle.grid( + columns: Int, + rows: Int, + marginX: Double = 0.0, + marginY: Double = 0.0, + gutterX: Double = 0.0, + gutterY: Double = 0.0 +): List> { + + val totalWidth = width - marginX * 2.0 + val totalHeight = height - marginY * 2.0 + + val totalGutterWidth = gutterX * (columns - 1).coerceAtLeast(0) + val totalGutterHeight = gutterY * (rows - 1).coerceAtLeast(0) + + val cellWidth = ((totalWidth - totalGutterWidth) / columns).coerceAtLeast(0.0) + val cellHeight = ((totalHeight - totalGutterHeight) / rows).coerceAtLeast(0.0) + + val cellSpaceX = cellWidth + gutterX + val cellSpaceY = cellHeight + gutterY + + val x0 = x + marginX + val y0 = y + marginY + + return (0 until rows).map { row -> + (0 until columns).map { column -> + Rectangle(x0 + column * cellSpaceX, y0 + row * cellSpaceY, cellWidth, cellHeight) + } + } +} \ No newline at end of file