james_womack
james_womack

Reputation: 10306

Rendering the layer of a UIWebView that contains an SVG file

I am attempting to use this method I've constructed to save the layer of a UIWebView as an image. That is working but the SVG I have loaded into the UIView is not getting rendered in the image, only the background of the 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;
}

In summary, I've loaded an SVG into a UIWebView, saved that UIWebView as an image, opened the image and the image does not have the SVG in it. I have done this with other views successfully, something is different about the SVG or UIWebView.

UPDATE: If I add a delay to make the app wait a few seconds to execute the image saving code then it works. Putting that code in webViewDidFinishLoad does NOT work. Obviously webViewDidFinishLoad doesn't count SVGs.

Upvotes: 1

Views: 1559

Answers (1)

james_womack
james_womack

Reputation: 10306

I have found that if you add a .1 second delay it will work

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

Upvotes: 1

Related Questions