Implementation of WebView screenshot in Android

The sharing methods of web pages in hybrid app tend to be more and more diversified. The more common user operation methods are: Copy Web page link, directly select target application, automatic sharing, etc. Among them, screenshot behavior has increasingly become one of the interactive ways that enrich user operations and are loved by users. We can see this function in many content community applications. This article summarizes the implementation of WebView screenshots in Android applications.

WebView, as a special control, naturally cannot obtain screenshots like other system views or screenshots (mostly long screenshots). For example:

If you use the above code on WebView, you will get a screenshot with incomplete content. In fact, the WebView system itself provides a corresponding API to obtain bitmap objects.

After obtaining the bitmap object, use this code to save it to the memory card of the device:

In two simple steps, you're done. However, when you operate on Android 5.0 and later devices, you will find that the screenshot display is not complete. Although the width and height of the picture meet the actual requirements, the content only includes the content of WebView in the current screen display area.

The reason is that in order to reduce memory consumption and improve performance, starting from Android 5.0, the system can intelligently select some HTML documents for rendering. Therefore, by default, we can only intercept the content of WebView in part of the screen display area, which leads to the above problem.

However, the system also provides a corresponding API to modify this default optimization behavior. The code is simple:

Note that this code must be added before the WebView instance is created. If an activity is used, it is in front of the setcontentview () method.

Although the capturepicture () method has been able to obtain WebView screenshots, it was abandoned by the system by API 19. Instead, use the OnDraw () method to get the bitmap object.

It should also be mentioned here that the getscale () method has been abandoned by the system since API 17. So another more elegant way to get the scale value is:

Finally, in the actual use process, we also need to consider the memory occupation of bitmap and do a good job in exception capture to prevent the occurrence of oom.

summary

The above is the implementation method of WebView screenshot in Android introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support of programming tips!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>