views:

248

answers:

1

I have overridden the drawRect: in my UIView and I want to draw several tiles. I'm looping through them all and I have a separate function that draws each individual tile.

The way I'm doing it now is I pass the tile's calculated CGRect to the function. At the moment, any drawing methods have to include the x & y offsets of the rect passed to it when drawing the tile images.

How can I push a new offset CGContext on the stack before calling the tile draw methods?

So for example, I could draw a square at [0, 0, 50, 50] inside the tile drawing method and that will actually be drawn at the correct tile's location?

+7  A: 

You should take advantage of the CTM (current transform matrix) which makes use of affine transforms to scale drawing into the context. It's built for exactly this purpose.

  • First call CGContextSaveGState. This saves a bunch of information about the graphics context onto a (per context) stack, including the CTM.
  • Secondly, use CGContextTranslateCTM. Pass in the x & y coordinates of the rect's origin.
  • Then call your drawing subroutine.
  • Finally, call CGContextRestoreGState. This will undo the translation.

Hope that helps.

Colin Barrett
Perfect, that was what I was looking for! Knew it would be something to do with stacks ;-)
Michael Waterfall
One possible improvement: You don't have to save and restore the gstate around every tile. You can `CGContextSaveGState` before an entire row, translate by <var>tile-width</var> points horizontally (and zero vertically) for each tile, then `CGContextRestoreGState` to get back to the beginning of the row and translate down by <var>tile-height</var> points to get to the next row.
Peter Hosey