Display doesn't clear properly after setNeedsDisplay

Discussion in 'iOS Programming' started by lunchlady55, Jul 27, 2009.

  1. lunchlady55 macrumors newbie

    Jul 27, 2009
    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];
    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.
  2. harry65 macrumors member

    Aug 26, 2008
    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);
  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Have you modified the clearsContextBeforeDrawing or opaque UIView properties for this view? They control this issue.
  4. lunchlady55 thread starter macrumors newbie

    Jul 27, 2009

    Hello, harry65 that solved my problem.

    Thanks for your help.

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

Share This Page