1

I create a drawing iOS application in which I would like to create a "Save Image" method. The drawing takes place inside the touchesMoved: method.

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

- (void) drawToCache:(UITouch*)touch {
    hue += 0.005;
    if(hue > 1.0) hue = 0.0;
    UIColor *color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0];

    CGContextSetStrokeColorWithColor(cacheContext, [color CGColor]);
    CGContextSetLineCap(cacheContext, kCGLineCapRound);
    CGContextSetLineWidth(cacheContext, 15);

    CGPoint lastPoint = [touch previousLocationInView:self];
    CGPoint newPoint = [touch locationInView:self];

    CGContextMoveToPoint(cacheContext, lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(cacheContext, newPoint.x, newPoint.y);
    CGContextStrokePath(cacheContext);

    CGRect dirtyPoint1 = CGRectMake(lastPoint.x-10, lastPoint.y-10, 20, 20);
    CGRect dirtyPoint2 = CGRectMake(newPoint.x-10, newPoint.y-10, 20, 20);
    [self setNeedsDisplayInRect:CGRectUnion(dirtyPoint1, dirtyPoint2)];
}

I would like to save what I have drawn to a .PNG file.

Is there a solution?

abg
  • 2,002
  • 7
  • 39
  • 63
  • possible duplicate of [How Do I Save What I have Drawn In A CGContext](http://stackoverflow.com/questions/2568421/how-do-i-save-what-i-have-drawn-in-a-cgcontext) – jrturton May 26 '12 at 07:33

2 Answers2

3

The solution is very straightforward:

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"myImage.png"];
Community
  • 1
  • 1
CrimsonDiego
  • 3,616
  • 1
  • 23
  • 26
  • This solution didn't work for me. File do not appear in my application folder (~/Library/Application Support/iPhone Simulator/5.1/Applications/CCAA9512-D2D6-4312-83D6-A4A9F74906C3/*). Where I should write this code? – abg May 24 '12 at 20:46
2

You need to actually set a path location. Expanding on CrimsonDiego's code, this will put the image in your /Documents directory of the App.

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"myImage.png"];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];
skram
  • 5,314
  • 1
  • 22
  • 26
  • I get an error on line "[imageData writeToFile:path];". Error: No visible @interface for 'NSData' declares the selector 'writeToFile:' – abg May 25 '12 at 06:41
  • Edited my answer with the correct method to use, writeToFile:atomically: – skram May 26 '12 at 07:15