如何将CGContextRef保存为.PNG文件?

我创build一个绘图iOS应用程序,我想创build一个“保存图像”方法。 绘图发生在touchesMoved:方法内。

- (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)]; } 

我想保存我所画的.PNG文件。

有解决scheme吗?

您需要实际设置path位置。 在CrimsonDiego的代码上进行扩展,这会将图像放在应用程序的/ Documents目录中。

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

解决scheme非常简单:

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