【问题标题】:How save CGContextRef as .PNG file?如何将 CGContextRef 保存为 .PNG 文件?
【发布时间】:2012-05-24 20:22:16
【问题描述】:

我创建了一个绘图 iOS 应用程序,我想在其中创建一个“保存图像”方法。 绘图发生在 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 文件中。

有解决办法吗?

【问题讨论】:

标签: ios cocoa-touch cgcontextref


【解决方案1】:

solution 非常简单:

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

【讨论】:

  • 这个解决方案对我不起作用。文件没有出现在我的应用程序文件夹中(~/Library/Application Support/iPhone Simulator/5.1/Applications/CCAA9512-D2D6-4312-83D6-A4A9F74906C3/*)。我应该在哪里写这段代码?
【解决方案2】:

您需要实际设置路径位置。扩展 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];

【讨论】:

  • 我在“[imageData writeToFile:path];”行收到错误。错误:“NSData”没有可见的@interface 声明选择器“writeToFile:”
  • 用正确的方法编辑了我的答案,writeToFile:atomically:
  • 如果这个答案对您有帮助,请接受。
相关资源