0

I am just learning Core graphics. So i have created a new project,include a UIView class. Now i have following code in my UIView implementation file

-(id) initWithCoder:(NSCoder*)sourceCoder
{
    if( ( self = [super initWithCoder:sourceCoder]))
    {
        //place any other initialization  here
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef    context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context,4);
    CGContextSetStrokeColorWithColor(context, myColor.CGColor);


    CGContextMoveToPoint(context,startPoint.x , startPoint.y);
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
    CGContextStrokePath(context);

}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch* touchPoint = [touches anyObject]; 
    startPoint = [touchPoint locationInView:self];
    endPoint = [touchPoint locationInView:self];

    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    endPoint=[touch locationInView:self];
    [self setNeedsDisplay];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];
    endPoint = [touch locationInView:self];
    [self setNeedsDisplay];
}

But it is just creating the line and if again i try to draw then the previous line is lost.

But i want the previous line should not lost, How can i do this?

user930195
  • 432
  • 1
  • 5
  • 19
  • See "How to use drawRect to draw in a existing view?" http://stackoverflow.com/questions/6724800/how-to-use-drawrect-to-draw-in-a-existing-view/6725315#6725315 – Rob Napier Oct 20 '11 at 00:16

2 Answers2

0

Set the view's clearsContextBeforeDrawing property to NO.

Jim
  • 72,985
  • 14
  • 101
  • 108
0

Set a UIImageView as background, save the context(lines) on there with:

CGContextStrokePath(UIGraphicsGetCurrentContext());
<your imageView>.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Wolfert
  • 974
  • 6
  • 12