Canvas Snap To Grid 2025 Update

image

Given that Scott Ferguson's original guide on snap to grid is now 11 years old, and many things have changed in AppInventor, I thought it was worth giving the method an update. It is still worth visiting Scott's solution topic, and also viewing of his youtube video, which explains the logic behind it all, in detail. So, all credits to @ScottFromScott for the method.

This update will also include the sprite cannibalism update I provided to Scott's original work, and also a procedure for generating a chess/chequers board.

BLOCKS

We start by setting two variables, one for the size of each square in the "grid", note that the canvas is set to 320x320, so 64 squares, and a variable to set the currentSprite selected (for handling cannibalism). I have all the imageSprites set to have their origin at 0.5/0.5, and they are sized 40x40pixels to match the squareSize.

blocks (11)

blocks (9)

Then we call the anyComponent ImageSprite TouchDown event, and set the currentSprite variable to the touched component

We need an anyComponent ImageSprite Dragged event, where we only drag if the component being dragged is the currentSprite. There is no need, as in the original guide, to set the imageSprites drag to centre, because their origins are at centre.

We then need the anyComponent ImageSprite TouchUp event, where the magic happens for the snap to grid. Because the imageSprites have their origin at centre, we need to add half the SquareSize to the x/y values for correct positioning. (Refer to Scott's video to understand the logic behind this)

The procedure for generating the chequer board:

A procedure for snapping to grid all imageSprites (on initialisation), which mimics the touch up event blocks. ( I have not accurately positioned the imageSprites in the designer)

Screen1.Initialise, which builds the chequer board

Video

AIA

snapToGrid2025.aia (106.2 KB)

The anyComponent blocks have greatly simplified things, and reduced block count, with the same result. It is worth noting that you do not have to have a chess board type background, this is for visual understanding only, your "grid" can simply be based upon, canvas size, squareSize and imageSprite size.

Here also an example with a 4x4 grid, plain background

snapToGrid2025Plain.aia (34.0 KB)

image

5 Likes

(added to FAQ)

Nice you can even change the background of the canvas by setting your screen color to the canvas.

Why don't you try and let us know.

1 Like