0

I have a customized UIView in which I do some low-level drawing in drawRect: method. It works fine when I instantiate the view in an XIB file. However, things go strange when I instantiate it programatically, e.g,

MyView *view = [[MyView alloc] initWithFrame: rect];

[self.view addSubView: view]; 

It appears that whenever drawRect: method runs, the resulting view contains the current drawing overlapped with some old drawings made in previous calls. In other words, it appears that the view has not been cleared out when drawRect: is called.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Wonka Gollum
  • 79
  • 1
  • 6
  • Where do you call the code you posted in your question? Perhaps you are adding multiple views. – rmaddy Jul 04 '13 at 05:11
  • What is the issue ? Which view is not clearing ? What you mean by current drawing ? – Midhun MP Jul 04 '13 at 05:23
  • My app updates the view by invoking its setNeedsDisplay method on a regular time interval. At each update, a new drawing is made within drawRect method. My problem is that this new (or current) drawing appears overlapped with some old drawings made in previous updates. – Wonka Gollum Jul 05 '13 at 00:53

2 Answers2

0

Let's check with this code in your viewDidLoad method or anywhere. And check about rect frame size should not be nill or 0.

- (void)viewDidLoad
{
    [super viewDidLoad];

    MyView *view = [[MyView alloc] initWithFrame: rect];

    NSLog(@"rect size %@  %@",NSStringFromCGRect(rect.bounds),NSStringFromCGRect(view.bounds));

    view.backGroundCOlor = [UIColor redColor];

    [self.view addSubView: view]; 
}

Check that it's working or not.

chandan
  • 2,453
  • 23
  • 31
  • My question did not say where I put my codes but the codes were within viewDidLoad method of the main view controller. So it was exactly same as what you suggested above (except for backgroundColor). So it's not working... – Wonka Gollum Jul 05 '13 at 00:47
0

I just found out that the cause of the problem is the backgroundColor property of the view set to nil.

I wonder if this is a bug since backgroudColor=nil is a valid value for transparent background. A possible explanation would be that the background color must be something other than transparent when custom drawing is done in the view's drawRect method, even though the current UIView class reference doesn't not ellaborate.

For clarity, this is what I did:

MyView *view = [[MyView alloc] initWithFrame: rect];
[self.view addSubView: view]; 
self.view.backgroundColor = [UIColor darkGrayColor];

I would appreciate if anybody can give a better explanation.

Wonka Gollum
  • 79
  • 1
  • 6