user278859
user278859

Reputation: 10519

Using UIGraphicsGetCurrentContext properly

II have a UIView into which I am placing 3 subviews, all instances of the same UIView, next to each other horizontally, filling each with a grey background. I got it to work for the first view but am having trouble with the second. Here is the drawRect code that is supposed to do the trick..

- (void)drawRect:(CGRect)rect {
        // grab current graphics context
    CGContextRef g = UIGraphicsGetCurrentContext();

       // fill grey background
    CGContextSetRGBFillColor(g, (207.0/255.0), (207.0/255.0), 211.0/255.0, 1.0);
    CGContextFillRect(g, self.frame);

}

So from my view controller I am creating the first subview with frame.origin.x = 0, and adding it to my main view, then creating the second with the frame.origin.x set to the width of the first and adding it, then the third.

The first view gets filled properly, but the second and third have black backgrounds as if the grey fill did not happen. I suspect that this is because I am not getting the context properly for the 2nd and 3rd subviews.

What do I have to do to make this work?

John

Upvotes: 0

Views: 3189

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

It's a geometry issue - frame vs bounds. You don't want to fill self.frame. Your drawRect should be:

- (void)drawRect:(CGRect)rect {
    // grab current graphics context
    CGContextRef g = UIGraphicsGetCurrentContext();

    // fill grey background
    CGContextSetRGBFillColor(g, (207.0/255.0), (207.0/255.0), 211.0/255.0, 1.0);
    CGContextFillRect(g, rect);
}

Upvotes: 3

Related Questions