I have a variable sized UIView with a drawRect containing CoreGraphics custom drawing code. The view was originally quite small but has the potential to become very wide and is placed inside a UIScrollView to enable the user to scroll through the view.
At the moment the view is created to be as wide as it needs to be to fit the entire drawing on and the CoreGraphics code draws across the entire view in drawRect.
- (void)drawRect:(CGRect)rect {
// Only try and draw if the frame size is greater than zero and the graph has some range
if ((self.frame.size.width>0) && (self.frame.size.height>0) && ((maxX - minX)>0)) {
// Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
// Save the state of the graphics context
CGContextSaveGState(context);
// Set the line style
CGContextSetRGBStrokeColor(context, 0.44, 0.58, 0.77, 1.0);
CGContextSetRGBFillColor(context, 0.44, 0.58, 0.77, 1.0);
CGContextSetLineWidth(context, 3.0);
CGContextSetLineDash(context, 0, NULL, 0);
// Draw the graph
[self drawGraphInContext:context];
// Restore the graphics context
CGContextRestoreGState(context);
}
}
I can make this more efficient by:
- Doing bounding calcs with the rect parameter in the
drawRectand only drawing stuff that is currently visible. - Creating a smaller
UIView(say 2x the width of the scrollView frame) and as the scroll position moves, redraw the image and re-centre the scrollView.
Before I go to the effort of doing either of these things, I would like to understand if it is worth the effort and whether I could run into problems later on if the UIView becomes very wide. So far performance is not an issue, but I am worried that memory might be.
Specifically, does the scrollView limit the amount of memory used by the view to the visible area? is the graphics context created the size of the entire view, the visible area or the size of the rect parameter? Are drawing operations outside the visible area simply ignored by CoreGraphics?
Any help and best practice advice would be appreciated.
IMO, it all depends on the
rectargument to the call:and as far as I know, this will be set to the
contentSizeof your scroll view. Simply, the context and the memory used for it will be related to thatrectvalue.You might trying doing your own “clipping” of the area you draw in by taking into account the
frameof the scroll view.Better yet, you could have a look at a sample by Apple about tiling content in a UIScrollView. It is sample 3.