渲染包含SVG文件的UIWebView层

时间:2011-03-02 07:02:52

标签: ios uiwebview svg

我试图使用我构建的方法将UIWebView的图层保存为图像。这是有效的,但我加载到UIView的SVG没有在图像中呈现,只有UIWebView的背景。

+ (BOOL)imageFromSVGinWebView:(UIView *)theView usePNG:(BOOL)usePNG; {  
    UIGraphicsBeginImageContext(theView.frame.size);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *layerIMGData = nil;
    NSString *pathComponent = nil;
    if (usePNG) {
        layerIMGData = UIImagePNGRepresentation(layerImage);
        pathComponent = @"png";
    }else {
        layerIMGData = UIImageJPEGRepresentation(layerImage,1.0f);
        pathComponent = @"jpg";
    }
    NSString *appFile = [[CCFileManagement conversionsDirectory] stringByAppendingPathComponent:String(@"img.%@",pathComponent)];
    NSError *error = nil;
    BOOL returnBOOL = [layerIMGData writeToFile:appFile options:NSDataWritingAtomic error:&error];
    if(error != nil)
        ILogPlus(@"%@",error);
    return returnBOOL;
}

总之,我已经将SVG加载到UIWebView中,将UIWebView保存为图像,打开图像并且图像中没有SVG。我已经成功完成了其他视图,SVG或UIWebView有所不同。

更新: 如果我添加一个延迟,让应用程序等待几秒钟来执行图像保存代码,那么它的工作原理。将该代码放在webViewDidFinishLoad中不起作用。显然webViewDidFinishLoad不计算SVG。

1 个答案:

答案 0 :(得分:1)

我发现如果你添加.1秒的延迟,它将起作用

- (void)webViewDidFinishLoad:(UIWebView *)webView; {
    [self performSelector:@selector(postLoadActions:) withObject:webView afterDelay:0.1f];
}


- (void)postLoadActions:(UIWebView *)webView; {
    if (![CCConversion imageFromSVGinWebView:webView usePNG:YES]) {
        ILogPlus(@"Didn't work");
    }
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[CCFileManagement conversionsDirectory] error:NULL];
    ILogPlus(@"%@",array);
    //[webView removeFromSuperview];
    [webView release];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[CCFileManagement conversionsDirectory] stringByAppendingPathComponent:@"img.png"]]];
    imageView.frame = CGRectMake(90, 90, imageView.frame.size.width, imageView.frame.size.height);
    imageView.backgroundColor = [UIColor clearColor];
    [self.view performSelector:@selector(addSubview:) withObject:imageView afterDelay:2.0f];
    [imageView release];
}