drawRect in Custom UIView off by height of navigation bar
I'm drawing a custom UIView that is sitting inside a xib whose ViewController is pushed onto a NavigationController.
Essentially the problem is that in the call to drawRect:(CGRect)rect
, rect has origin at (0,0) when it should have origin at (0,nav_bar_height). Therefore, the following code, which draws an image
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
// set up the image
UIImage * img = [UIImage imageWithData:someData];
// flip the image to the correct orientation
CGContextTranslateCTM(context, 0, rect.size.height + rect.origin.y );
CGContextScaleCTM(context, 1, -1);
// draw the image
CGContextDrawImage(context, rect, [img CGImage]);
UIGraphicsPopContext();
}
This will cut off the top 30 pixels or so of the imag开发者_高级运维e and leave empty the bottom 30.
How can I account for the navigation bar height?
Without knowing more about your view-structure, I risk being unhelpful, but let me know if the following helps at all: instead of using the rect
parameter, which can be sort of unpredictable, try using the bounds
of your custom view. In reality, I can't imagine why you'd be having this problem, unless your view is being overlapped with the navigation bar; I'd suggest checking to be sure this isn't so, in any case. Best of luck!
Update
Looks like that didn't help. Just offset your y
parameter by self.navigationController.navigationBar.bounds.size.height
. So your code should look like:
//...
CGFloat dy = self.navigationController.navigationBar.bounds.size.height;
CGRect r = CGRectMake(rect.origin.x,rect.origin.y + dy, rect.size.width, rect.size.height - dy);
//...
CGContextDrawImage(context,r,img.CGImage);
//...
I hope that was more helpful.
精彩评论