PDA

View Full Version : Display doesn't clear properly after setNeedsDisplay




lunchlady55
Jul 27, 2009, 07:00 PM
Here's the offending code (I believe):


@implementation Fraction

-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
numerator = 3;
denominator = 4;
location = CGPointMake(160, 240);
}
return self;
}

-(void)drawRect:(CGRect)rect {
// Drawing code
NSMutableString *fraction = [NSString stringWithFormat:@"%d/%d", numerator, denominator];
UIFont *font = [UIFont systemFontOfSize:30];
[[UIColor whiteColor] set];
[fraction drawAtPoint:location withFont:font];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// We only support single touches, so anyObject retrieves just that touch from touches
UITouch *touch = [touches anyObject];
numerator = numerator + 1;
location = [touch locationInView:self];
[self setNeedsDisplay];

return;
}


The display shows 3/4 in the middle of the screen as I expect, and upon first touch, the display clears and shows 4/4 at the point touched. But on the 2nd touch, 5/4 appears, but 3/4 reappears. 3rd touch, both 5/4 & 3/4 clear, 6/4 displays, but 4/4 reappears. This pattern continues upon all subsequent touches, (all even numerator show or all odd numerators show.) Strangest of all, when I wait ~10-20 seconds between touches, the old ones will NOT reappear upon the next touch. I fear that this is some kind of timer in the UIKit that I don't know about/understand.

Anyone have any ideas on how to avoid this issue? Is there some clear screen buffer function I'm not aware of?

Thank you.



harry65
Jul 27, 2009, 08:47 PM
When drawRect is called, the drawing happens in the current graphics context. If you don't specify one it just uses the current one. I'm guessing what's happening is it's using context1, then context2, and it keeps switching back and forth. That is why the even numbers show up once, and then the odd numbers.

If you add the following the the beginning of drawRect, it should fix your problem:


CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);

PhoneyDeveloper
Jul 27, 2009, 09:11 PM
Have you modified the clearsContextBeforeDrawing or opaque UIView properties for this view? They control this issue.

lunchlady55
Jul 28, 2009, 08:57 AM
Hello, harry65 that solved my problem.

Thanks for your help.

PhoneyDeveloper, I'll check out the clearsContextBeforeDrawing and setting the UIView as opaque.