Image Splitter — Swift source
Split an image into an even grid of tiles — rows × columns with a live cut-line preview and per-tile or bulk PNG download. Runs entirely in your browser.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Image splitter — tile geometry — Swift port of the image-splitter tool.
/// One cut of the grid: the source rectangle that becomes a tile. In the
/// browser tool this rect is drawImage'd into its own canvas and encoded
/// to PNG; the geometry here is the deterministic part of that pipeline.
struct TileRect: CustomStringConvertible {
let x: Int, y: Int, width: Int, height: Int
var description: String { "src=(\(x), \(y)) \(width)x\(height)" }
}
enum ImageSplitter {
/// Split a width x height image into rows x cols tiles, row-major.
/// Mirrors splitToTiles in typescript.ts: tileW = floor(width / cols),
/// tileH = floor(height / rows) — Int division IS Math.floor for
/// positives, so a 1024px width over 3 cols yields 341px tiles and the
/// last 1px column is dropped, exactly like the TS.
static func splitTiles(width: Int, height: Int, rows: Int, cols: Int) -> [TileRect] {
let tileW = width / cols
let tileH = height / rows
return (0..<rows).flatMap { row in
(0..<cols).map { col in
TileRect(x: col * tileW, y: row * tileH, width: tileW, height: tileH)
}
}
}
}
// 1024x768 image, 2 rows x 3 cols -> six 341x384 tiles.
for tile in ImageSplitter.splitTiles(width: 1024, height: 768, rows: 2, cols: 3) {
print(tile)
}
Also available in 8 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →