WKWebView Screenshots

前端 未结 4 918
天命终不由人
天命终不由人 2021-02-08 06:59

I am trying to capture the image that the webview is displaying to the user, so I can some color analysis of the web page. When I try to get the image from it\'s parent, I am ba

4条回答
  •  误落风尘
    2021-02-08 07:40

    I realise the question was for Mac OS X, but I found this page whilst searching for an iOS solution. My answer below doesn't work on Mac OS X as the drawViewHierarchyInRect() API call is currently iOS only, but I put it here for reference for other iOS searchers.

    This Stackoverflow answer solved it for me on iOS 8 with a WKWebView. That answer's sample code is in Objective-C but the Swift equivalent to go in a UIView sub-class or extension would be along the lines of the code below. The code ignores the return value of drawViewHierarchyInRect(), but you may want to pay attention to it.

    func imageSnapshot() -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0);
        self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true);
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return snapshotImage;
    }
    

提交回复
热议问题