0

I am using this link(http://www.raywenderlich.com/18840/how-to-make-a-simple-drawing-app-with-uikit) for making a paint application and I want to perform a undo operation as well.

I used this code to save every sketch made by the user in an mutable `array[completeLines]. These changes are done in touchesEnded method

**UIGraphicsBeginImageContextWithOptions(_tempDrawImage.bounds.size, NO,0.0);
[_tempDrawImage.image drawInRect:CGRectMake(0, 0, _tempDrawImage.frame.size.width, _tempDrawImage.frame.size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
[completeLines addObject:image];**

And, on pressing the undo button I want to remove the last sketch from the view. Help me out in getting out the image reference from the mutable array and to remove it from the view.

user3275031
  • 39
  • 1
  • 1
  • 4

1 Answers1

0

While what you're doing may work in the short term it will eventually fail when you have too many images to store (either in memory or on disk). So, going forwards you will need to store your drawing history information in some other format.

Anyway, basically, when you undo you want to:

  1. Remove the current (last) image from the array (depends on when you're adding images)
  2. Set the entire view as needing display
  3. Get the new last image from the array
  4. Replace your current drawing view contents with that image

Replacing your drawing view contents means clearing the drawing context and drawing the saved image into it. This can be a little messy as it means having logic in your drawRect: method (assuming you have no backing layer for drawing into). You could save a property which says redraw and then:

if (self.redraw) {
    // clear the context
    // draw the last image

    self.redraw = NO;
}

// draw your new painting (appending to the graphics context)

It would be better to have a separation of your 'committed' content and your current painting (the in-progress touch result). Now, when you undo you, outside drawRect:, update the backing layer to roll back the content. This means that drawRect: doesn't have any logic as it is just drawing the committed content and the current content all the time. This could be done with 2 CALayer instances, 1 with a content image and 1 with a delegate to draw the current painting.

Wain
  • 118,658
  • 15
  • 128
  • 151