Posted: 4th Mar 2014 2:15
A tileset image is an image made up of multiple square tiles as used for a tile-based game. With AppGameKit, you can load this single image and use the animation commands to break apart the tiles. But sometimes, these tilesets have spacing and margins around each tile in the image and AppGameKit has no way to account for this when building the animation frames. This is a convenience function to get around that without having to alter the image yourself with an image editor.

Specify the filename of the image to load, and the width and height of a tile. Margin is the area around the top and left of a tile. Spacing is the area on the bottom and right side of a tile. The function will rebuild the image without all the spacing and margin and return an image ID.

+ Code Snippet
function getTrimmedImage(filename$, tileWidth, tileHeight, margin, spacing)
    img = loadImage(filename$)
    m1  = createMemblockFromImage(img)
    imgWidth   = getImageWidth(img)
    imgHeight  = getImageHeight(img)
    tileCountX = (imgWidth-margin)  / (tileWidth  + spacing)
    tileCountY = (imgHeight-margin) / (tileHeight + spacing)
    // Don't need image anymore, it's in the memblock
    deleteImage(img)

    // Loop through all tiles
    for ty = 0 to tileCountY-1
        for tx = 0 to tileCountX-1
            // Find starting position of this tile
            rows = ((ty*(tileHeight+spacing))+margin)
            cols = tx*(tileWidth+spacing) + margin
            base = (rows*imgWidth)*4 + cols*4 + 12

            // Tile pixels
            for y = 0 to tileHeight-1
                for x = 0 to tileWidth-1
                    pos1 = base + (y*imgWidth + x)*4
                    junk = (ty*spacing+margin)*imgWidth*4 + (tx*spacing+margin)*4
                    pos2 = pos1 - junk
                    setMemblockInt(m1, pos2, getMemblockInt(m1, pos1))
                next x
            next y
        next tx
    next ty

    // Dimensions of new image stripped of margin and spacing
    newWidth  = tileCountX*tileWidth
    newHeight = tileCountY*tileHeight


    createImageFromMemblock(img, m1)
    img1 = copyImage(img, 0, 0, newWidth, newHeight)

    deleteMemblock(m1)
endfunction img1