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:?
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:.