Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding drawRect: and pushing new offset CGContexts onto the stack

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?

like image 939
Michael Waterfall Avatar asked Nov 21 '25 08:11

Michael Waterfall


1 Answers

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.

like image 102
Colin Barrett Avatar answered Nov 23 '25 22:11

Colin Barrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!