Transforming a Pixel to a Tile Coordinate

To perform pan and zoom, and locate items in a particular map tile, you need to be able to determine which tile a pixel is in. To do this the client must be able to calculate the column and row or the tile when given a coordinate in pixels. To perform this step, and transform a pixel into a tile coordinate, you can use the following calculations:

  1. Calculate the tile column:

    col = (pixelX ÷ tileWidth) + 1
  2. Calculate the tile row:

    row = (pixelY ÷ tileHeight) + 1

It is important to remember that the pixel location is relative to the map's pixel space and not the screen space. It may not be enough to directly feed a pixel coordinate from a mouse location on the screen. For instance, you may have to convert the mouse location to a location in the map's pixel space. This involves keeping track of the location in map pixels space of the upper right-hand corner of the image control and offsetting the mouse location with that location.