将uiview转换为.png图像

时间:2012-05-25 04:59:25

标签: iphone objective-c xcode

我正在研究iphone并且我采用了UIView的子类,并且在绘制rect方法中我正在进行一些设计。我想以.png格式转换此视图。

提前致谢。

2 个答案:

答案 0 :(得分:22)

    UIGraphicsBeginImageContext(myView.frame.size);
    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data=UIImagePNGRepresentation(viewImage);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
    [data writeToFile:strPath atomically:YES];

答案 1 :(得分:0)

   UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(YourView.frame.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(keyWindow.bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil); 
    UIGraphicsEndImageContext();