开发者

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 callin开发者_运维技巧g 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜