将CGPath绘制到UIView,然后将视图保存为Png

时间:2011-10-20 14:14:07

标签: ios4 uiimage drawing

在UIView的drawrect函数中,我使用CGContext绘制一些形状。这工作正常,我可以看到我的形状。 现在我试图将视图上绘制的内容保存为磁盘上的png。我已经阅读了各种文档/文章但没有得到任何保存。我在模拟器上测试ios 4.3。

修改1

我更改了代码并取消注释了上下文部分。我可以保存png,但它是空白的。

- (void)drawRect:(CGRect)rect
{

    CGContextRef ctx= UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(ctx, 0, 0, 0, .5);
    CGContextBeginPath(ctx);
    CGContextAddPath(ctx, mutatablepath);
    //CGContextStrokePath(ctx);
    CGContextFillPath(ctx);
    CFRelease(mutatablepath);




    NSString *path0;
    NSArray *paths0=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    path0=[[paths0 objectAtIndex:0]stringByAppendingPathComponent:@"images"];
    NSError *error;

    if (![[NSFileManager defaultManager]fileExistsAtPath:path0]) {

        if(![[NSFileManager defaultManager]createDirectoryAtPath:path0 withIntermediateDirectories:NO attributes:nil error:&error])

        {
            NSLog(@"Create directory error %@",error);

        }
    }




    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSData *imagedata=UIImagePNGRepresentation(image);

    NSString *namepath=[NSString stringWithFormat:@"%@.png",@"test"];
    NSString *path;
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    path=[[paths objectAtIndex:0]stringByAppendingPathComponent:@"images"];
    NSString *savepath=[NSString stringWithFormat:@"%@/%@",path,namepath ];


    // NSError 

    NSLog(@"%@",savepath);

    [imagedata writeToFile:savepath atomically:YES];


}

1 个答案:

答案 0 :(得分:0)

您可以使用drawRect方法中的图像保存代码来执行此操作,因为renderInContext方法会根据需要隐式调用drawRect

UIView *myView = [[MyViewClass alloc] initWithFrame:CGRectMake(/*...*/)];
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

来源:http://pastie.org/244916