So you want to snap the sprite to align with the grid?
My code assumes the sprite's origin is its center.
gridSize = 64
// Determine which grid square the sprite is in
gridX = floor(getSpriteXByOffset(1) / gridSize)
gridY = floor(getSpriteYByOffset(1) / gridSize)
// This determines the left edge of the sprite
x1 = getSpriteXByOffset(1) - (getSpriteWidth(1)/2)
// This finds the left edge of the grid tile
gx = gridX * gridSize
// Distance of red line:
d = x1 - gx
To look correct, you'll want to snap the sprite to whichever grid square the center of your sprite falls into. Visually, it'll just make more sense to the user that way. My code gives a solution to the illustration, but I'm assuming that line could be on any of the 4 sides around the sprite? To know which distance you need to calculate, look at where the center of the sprite is in relation to the center of that grid square. You picture shows it right of center. If it's left of center than you'll be calculating the right edge of the sprite from the right edge of that grid square. Same rule applies for vertical distance.