Search code examples
iphonepathdrawshapescg

Line is erased when drawing shapes


I am trying to make an application for drawing shapes on screen by touching it.

I can draw a line from one point to another- but it erases on each new draw.

Here is my code:

CGPoint location;
CGContextRef context;
CGPoint drawAtPoint;
CGPoint lastPoint;
-(void)awakeFromNib{
    //[self addSubview:noteView];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    location = [touch locationInView:touch.view];
    [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)];
}

- (void)drawRect:(CGRect)rect {
    context = UIGraphicsGetCurrentContext();
    [[UIColor blueColor] set];
    CGContextSetLineWidth(context,10);
    drawAtPoint.x =location.x;
    drawAtPoint.y =location.y;
    CGContextAddEllipseInRect(context,CGRectMake(drawAtPoint.x, drawAtPoint.y, 2, 2));
    CGContextAddLineToPoint(context,lastPoint.x, lastPoint.y);
    CGContextStrokePath(context);

    lastPoint.x =location.x;
    lastPoint.y =location.y;
}

Appreciate your help-

Nir.


Solution

  • As you have discovered, -drawRect is where you display the contents of a view. You will only 'see' on screen what you draw here.

    This is much more low-level than something like Flash where you might add a movieclip containing a line to the stage and some time later add another movieclip containing a line to the stage and now you see - two lines!

    You will need to do some work and prdobably set up something like..

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    
        UITouch *touch = [[event allTouches] anyObject]; 
        location = [touch locationInView:touch.view]; 
    
        [self addNewLineFrom:lastPoint to:location];
    
        lastPoint = location;
    
        [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)]; 
    }
    
    - (void)drawRect:(CGRect)rect {
    
        context = UIGraphicsGetCurrentContext();
    
        for( Line *eachLine in lineArray )
            [eachLine drawInContext:context];
    
    }
    

    I think you can see how to flesh this out to what you need.

    Another way to approach this is to use CALayers. Using this approach you dont draw inside - - (void)drawRect at all - you add and remove layers, draw what you like inside them, and the view will handle compositing them together and drawing to the screen as needed. Probably more what you are looking for.