How Do I Save What I have Drawn In A CGContext

2019-02-05 01:28发布

I have drawn into a CGContext of a UIView.

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

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];
}

3条回答
Viruses.
2楼-- · 2019-02-05 01:29
CGImageRef imgRef = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:imgRef];

CGImageRelease(imgRef);
查看更多
甜甜的少女心
3楼-- · 2019-02-05 01:30

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.

查看更多
放我归山
4楼-- · 2019-02-05 01:36
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png"];
查看更多
登录 后发表回答