0

I have a UIView subclass with the drawRect: method overriden. In there, I have long lines of generated code that draw something.

The generated code has a problem of having all the vertices/coordinates of the paths/lines hard-coded. So, to draw a 100x100 square, it would start at 0,0 and go to 0,100 -> 100,100 -> 100,0. To make this shape scale based on the UIView bounds property was done as follows:

// This is the size of the drawing. I always know this value beforehand.
CGSize contentSize = SHAPE_XMARK_SIZE;
CGFloat scaleX = self.bounds.size.width / contentSize.width;
CGFloat scaleY = self.bounds.size.height / contentSize.height;

CGContextScaleCTM(context, MIN(scaleX, scaleY), MIN(scaleX, scaleY));

All good as far as the scale is concerned. Now, I would like the position of the drawing to be ralative to the bounds, too. I want to somehow make the drawRect: method align the drawing based on the bounds, too.

I am thinking of something like:

  1. push context method
  2. draw code
  3. pop context
  4. position previous context

Is that a sane approach? Or is the push and pop context not able to accomplish such sorcery?


One Simple Approach:

To answer the "what have you tried" question, I tried making the view that I draw isolated with a bounds size equal to the drawing size, then embed that view inside another view... and it works. However, this method is tedious and I would prefer avoiding it, if possible.

Mazyod
  • 22,319
  • 10
  • 92
  • 157

1 Answers1

0

Pfft, the answer was super simple. Me 1, SO 0, I guess.

CGContextTranslateCTM(context, xOffset, yOffset);

Yeah, I somehow overlooked the fact that an awesome function should exist to translate CGContextRef, since the scale function existed.

The rest is all simple math to achieve vertical & horizontal alignment.

Mazyod
  • 22,319
  • 10
  • 92
  • 157