Convert UIWebview contents to a UIImage when the webview is larger than the screen

后端 未结 5 1157
孤城傲影
孤城傲影 2020-12-02 19:20

Very similar to this question (and also this answer), I\'m trying to make an UIImage out from a webview. So far I\'m using the code suggested in the answer, specifically: <

5条回答
  •  抹茶落季
    2020-12-02 20:24

    I got the answer:

    You have to set the frame of the Webview to the full content size just before you create the image. After this just set the size back to origin:

    + (UIImage *) imageFromWebView:(UIWebView *)view
    {
        // tempframe to reset view size after image was created
        CGRect tmpFrame         = view.frame;
    
        // set new Frame
        CGRect aFrame               = view.frame;
        aFrame.size.height  = [view sizeThatFits:[[UIScreen mainScreen] bounds].size].height;
        view.frame              = aFrame;
    
        // do image magic
        UIGraphicsBeginImageContext([view sizeThatFits:[[UIScreen mainScreen] bounds].size]);
    
        CGContextRef resizedContext = UIGraphicsGetCurrentContext();
        [view.layer renderInContext:resizedContext];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        // reset Frame of view to origin
        view.frame = tmpFrame;
        return image;
    }
    

提交回复
热议问题