0

I have this code which makes multiple rectangles in a UIView:

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(ctx, 0.5);

CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor);

//newView.xPoints is always equal in count to the other two arrays below.    
for (int i = 0; i < [newView.xPoints count]; i++) 
{
    CGFloat tx = [[newView.xPoints objectAtIndex:i]floatValue];
    CGFloat ty = [[newView.yPoints objectAtIndex:i]floatValue];
    CGFloat charWidth = [[newView.charArray objectAtIndex:i]floatValue];

    CGRect rect = CGRectMake(tx, (theContentView.bounds.size.height - ty), charWidth, -10.5);
    CGContextAddRect(ctx, rect);
    CGContextStrokePath(ctx);
}

I tried it in drawRect: and it worked perfectly fine. However, I plan to use drawRect: for other purposes. So can anyone give me tips or hints on how to do it without using drawRect:?

jscs
  • 63,694
  • 13
  • 151
  • 195
user1412469
  • 279
  • 5
  • 17
  • 1
    You can do multiple things in drawRect, you know. You can wrap that code in a function and call it from draw rect. – EightyEight Jul 09 '12 at 05:33

2 Answers2

2

You can't. Inside of drawRect: is the only time that the current context is going to the screen. You will have to make your "other purposes" co-exist with this rectangle drawing code.

You can, however, factor this code out to another method, as long as it is only called from inside drawRect:.

jscs
  • 63,694
  • 13
  • 151
  • 195
2

You can't. The only time UIGraphicsGetCurrentContext() is valid for your view is inside drawRect:. You can draw to a layer outside of drawRect, but still you will have to draw that layer to your view in drawRect: if you want to actually see it.

borrrden
  • 33,256
  • 8
  • 74
  • 109