How save CGContextRef as .PNG file?

ぐ巨炮叔叔 提交于 2020-01-05 08:50:13

问题


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?


回答1:


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];



回答2:


The solution is very straightforward:

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"myImage.png"];


来源:https://stackoverflow.com/questions/10744738/how-save-cgcontextref-as-png-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!