nonopolarity
nonopolarity

Reputation: 150976

On iOS, drawRect cannot draw outside of the view's bounds?

I thought from some point on for OS X, and always true for iOS, that content can appear outside of the view's bounds? (for UIView) But if I create a brand new Single View app, and created a MyView class that subclasses UIView, and implement its drawRect:

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:
                                           CGRectMake(-20, -20, 600, 600)];
    [[UIColor greenColor] set];
    [path fill];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor blueColor] CGColor]);
    CGContextFillRect(context, CGRectMake(-20, -20, 600, 600));
}

I use both UI and CG to draw a rectangle each, just in case one works and the other doesn't. And the view is added in viewDidAppear:

- (void)viewDidAppear:(BOOL)animated {
    MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(20, 20, 260, 260)];
    [self.view addSubview:myView];
}

But no matter what, the colored box won't go beyond the (20, 20, 260, 260) region. Is it true that only the CALayers can be freely added and appear outside of a view's bounds? Can it be because of the graphics context is limited to this (20, 20, 260, 260) to begin with? If so, is there a way to make drawRect content appear outside of the view's bound, in all four top, down, left, right directions?

Upvotes: 23

Views: 11099

Answers (2)

Tim Kokesh
Tim Kokesh

Reputation: 879

Your problem is that "drawRect" is automatically clipped to the view that you are drawing in.

Instead of doing the drawing in the view itself, add a second (sub)view to the first view, that is outside the bounds of the first view. This will allow you to do drawing that is dependent on the placement of the first view, but is outside the first view's bounds.

Hope this helps.

Upvotes: 31

Lefteris
Lefteris

Reputation: 14667

Try this on a view, where you have added the scrollView:

self.scrollView.backgroundColor = [UIColor darkGrayColor];
self.scrollView.layer.cornerRadius = 10.0f;
self.scrollView.layer.masksToBounds = YES;

It should display a gray scrollview with rounded corners, as you want.

Remember you need to import the QuartzCore FrameWork

Upvotes: -3

Related Questions