Jason Renaldo
Jason Renaldo

Reputation: 2822

UIView not setting background color in drawRect

I created a class that subclasses UIView. In the drawRect, I have what should be drawing a orange colored rectangle. Yet it shows up as black.

In my custom class:

#import "testRect.h"

@implementation testRect

- (id)initWithFrame:(CGRect)frame
{
     self = [super initWithFrame:frame];
     if (self) {

     }
     return self;
}


- (void)drawRect:(CGRect)rect
{
   //// Color Declarations
   UIColor* strokeColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 1];
   UIColor* fillColor2 = [UIColor colorWithRed: 0.886 green: 0.59 blue: 0 alpha: 1];

   //// Rectangle Drawing
   UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(26.5, 171.5, 265, 139)];
   [fillColor2 setFill];
   [rectanglePath fill];
   [strokeColor setStroke];
   rectanglePath.lineWidth = 1;
   [rectanglePath stroke];
}

And my viewcontroller

#import "ViewController.h"
#import "testRect.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    testRect *test = [[testRect alloc] initWithFrame:CGRectMake(10, 10, 265, 139)];
    [self.view addSubview:test];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

Upvotes: 0

Views: 1353

Answers (1)

rmaddy
rmaddy

Reputation: 318854

The CGRect used in your drawRect: method is incorrect. You want a CGRect that is relative to the view. This means the origin will be 0,0. Also, the rect should be calculated at runtime based on the view's bounds. Do not hardcode it in drawRect:. This will make the code work properly regardless of what frame is used to create the view.

The rect you use now (in drawRect: has a y-origin of 171.5 but the view's height is only 139. So all of the drawing you do is outside of the view. That is why it appears black.

You probably want:

CGRect bounds = self.bounds;
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect:bounds];

Upvotes: 1

Related Questions