Set background color for only part of UIView

AllieCat picture AllieCat · Aug 5, 2013 · Viewed 19.5k times · Source

I want the bottom (not quite half) of my UIView to be a different color than the top.

I'm wondering if I should create a CGRect and then color that? Is this along the right track?

- (void)drawRect:(CGRect)rect { 

    CGRect aRect = CGRectMake(x, y, width, height);

    // Fill the rectangle with grey
    [[UIColor greyColor] setFill];
    UIRectFill( rect );
}

Answer

Lucas Eduardo picture Lucas Eduardo · Aug 5, 2013

Yes, as you are already overriding drawRect method, this will do.

- (void)drawRect:(CGRect)rect { 

    CGRect topRect = CGRectMake(0, 0, rect.size.width, rect.size.height/2.0);
    // Fill the rectangle with grey
    [[UIColor greyColor] setFill];
    UIRectFill( topRect );

    CGRect bottomRect = CGRectMake(0, rect.size.height/2.0, rect.size.width, rect.size.height/2.0);
    [[UIColor redColor] setFill];
    UIRectFill( bottomRect );

}

Change the values inside the frames as you wish.