如何将绘制的内容保存在CGContext中

问题描述 投票:0回答:4

我已经绘制到 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
4个回答
7
投票
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png" atomically:YES];

6
投票
CGImageRef imgRef = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:imgRef];

CGImageRelease(imgRef);

1
投票

调用

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


0
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.