我已经绘制到 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];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png" atomically:YES];
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
调用
UIGraphicsGetImageFromCurrentImageContext
获取 UIImage。UIImagePNGRepresentation
获取以 PNG 编码的 UIImage 的 NSData。-writeToFile:…
保存 NSData。
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)