UIWebView and Wkwebview have different screenshots:
UIWebView:
func getImage (context:serviceexecutecontext), UIImage {//Create a bitmap-based graphic up and down Text and specify size uigraphicsbeginimagecontextwithoptions (context.fromViewController.webView.bounds.size, True, 0)//ren Derincontext renders the recipient and its child scopes to the specified context Context.fromViewController.webView.layer.renderInContext ( Uigraphicsgetcurrentcontext ()!) Returns a picture based on the current graphics context let image = Uigraphicsgetimagefromcurrentimagecontext ()//Removes the top of the stack based on the current bitmap's graphics context Uigrap Hicsendimagecontext ()//let imagref = Cgimagecreatewithimageinrect ((image?. cgimage)!, context.fromViewController.webView.bounds)//let newimage = Uiimage.init (cgimage:imagref!) Uiimagewritetosavedphotosalbum (newimage, nil, nil, nil);//Save the picture to the photo gallery return image! }
The Uigraphicsbeginimagecontext () method passes in a unique parameter, which is a cgsize variable that specifies the size of the graphics context, so this size is the size of the screen when getting the screen. Actually understand this process, know that this method can get any area, of course, must be part of the current page. You need to intercept which view image, let the view layer call Renderincontext to render the graph into the current graph context.
Wkwebview:
When I try to intercept Wkwebview's diagram. The result returned to me was just a background picture, apparently failed. By searching for StackOverflow and Google, I found that Wkwebview could not simply use layer.renderInContext
the method to draw graphics. If the direct call layer.renderInContext
needs to get the corresponding context, but the return result that is executed in Wkwebview UIGraphicsGetCurrentContext()
is nil
StackOverflow provides a solution UIView
to the idea of using the drawViewHierarchyInRect
method to intercept the screen view. By calling Wkwebview directly drawViewHierarchyInRect
( afterScreenUpdates
parameters must be true
), you can successfully intercept Wkwebview screen content
Func getImage (context:serviceexecutecontext), UIImage { uigraphicsbeginimagecontextwithoptions ( Context.fromViewController.webView.bounds.size, True, 0) for Subview:uiview in context.fromViewController.webView.subviews { Subview.drawviewhierarchyinrect (subview.bounds, afterscreenupdates:true) } //uiapplication.sharedapplication (). Keywindow?. Layer.renderincontext (Uigraphicsgetcurrentcontext ()!) Let image = Uigraphicsgetimagefromcurrentimagecontext () uigraphicsendimagecontext () //let imagref = Cgimagecreatewithimageinrect (image?. cgimage)!, context.fromViewController.webView.bounds) //let newimage = Uiimage.init (cgimage:imagref!) Return image! }
http://blog.csdn.net/haoziy1989511/article/details/50856178
IOS screenshot of current WebView