【问题标题】:How Do I Save What I have Drawn In A CGContext如何保存我在 CGContext 中绘制的内容
【发布时间】:2010-04-02 18:31:33
【问题描述】:

我已绘制到 UIView 的 CGContext 中。

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]  
}

我想将我绘制的内容保存到 png 文件中。

有简单的解决办法吗?

编辑:根据以下建议 - 这是我目前所拥有的......

-(void)createImage {
    NSString* outFile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/image.png"];
    DLog(@"creating image file at %@", outFile);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:outFile 
                atomically:NO];
}

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]; 
    [self createImage];
}

【问题讨论】:

  • 或许更好的问题是如何创建位图上下文并将我的绘图重播到其中。

标签: iphone cocoa-touch uiview


【解决方案1】:
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png"];

【讨论】:

  • 我一定遗漏了一些简单的东西。我在 drawRect 调用中执行此操作。在 iPhone 模拟器上运行 - 我没有看到任何创建的文件。
  • 您可能需要指定 Documents 目录的完整路径,而不仅仅是 image.png。
  • 我更新了上面的示例代码 - 但没有在模拟器中创建文件。不过感谢您的帮助。
【解决方案2】:
CGImageRef imgRef = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:imgRef];

CGImageRelease(imgRef);

【讨论】:

  • 不要只是发布代码作为答案,尝试解释一下为什么这会有所帮助。
【解决方案3】:

调用 UIGraphicsGetImageFromCurrentImageContext 获取 UIImage。
然后调用UIImagePNGRepresentation获取PNG编码的UIImage的NSData。
最后调用-writeToFile:…保存NSData。

【讨论】:

    【解决方案4】:
    let imageWidth = inputCGImage.width
    let imageHeight = inputCGImage.height
    
    let imageRect = NSRect(
        origin: .zero,
        size: CGSize(width: imageWidth, height: imageHeight)
    )
    
    context.draw(inputCGImage, in: imageRect)
    
    let outputImageRef = context.makeImage()!
    
    let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true) as [String]
    
    let destinationURL = NSURL(fileURLWithPath: paths.first!).appendingPathComponent("output.png")!
    
    guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else {
        throw HoleFillingError.CoreGraphicsError
    }
    
    CGImageDestinationAddImage(destination, outputImageRef, nil)
    CGImageDestinationFinalize(destination)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多