开发者

How Do I Save What I have Drawn In A CGContext

开发者 https://www.devze.com 2022-12-25 05:51 出处:网络
I have drawn into a CGContext of a UIView. - (void)drawRect:(CGRect)rect { [self drawInContext:UIGraphicsGe开发者_JAVA百科tCurrentContext()]

I have drawn into a CGContext of a UIView.

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGe开发者_JAVA百科tCurrentContext()]  
}

I would like to save what I have drawn to a png file.

Is there a simple solution?

EDIT: Based on suggestions below - here's what I have so far....

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


CGImageRef imgRef = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:imgRef];

CGImageRelease(imgRef);


Call UIGraphicsGetImageFromCurrentImageContext to get an UIImage.
Then call UIImagePNGRepresentation to get an NSData of the UIImage encoded in PNG.
Finally, call -writeToFile:… to save the 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消