要在WebView中顯示網(wǎng)頁灰度顯示,您可以通過以下步驟操作:
使用的原理兩種方式,一種使用畫筆,一種是js css注入。都能夠?qū)崿F(xiàn)黑白色灰度網(wǎng)頁。
在您的布局文件中添加WebView組件:
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在您的Activity或Fragment中,初始化WebView并啟用硬件加速:
WebView webView = findViewById(R.id.webview);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
創(chuàng)建applyGrayscaleFilter()方法,該方法將會應(yīng)用灰度濾鏡到WebView的內(nèi)容:
@SuppressWarnings({"deprecation", "AccessStaticViaInstance"})
private void applyGrayscaleFilter(WebView webView) {
// 創(chuàng)建WebSettings實(shí)例
WebSettings webSettings = webView.getSettings();
// 啟用插件
webSettings.setPluginState(WebSettings.PluginState.ON);
// 根據(jù)系統(tǒng)版本選擇不同的濾鏡方法
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);// 0為黑白色
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Android 10及以上版本
webView.setWebContentsDebuggingEnabled(true);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webView.setRendererPriorityPolicy(RENDERER_PRIORITY_BOUND, true);
// 兩種方法都可以
//nativeHandleGrey(view, filter);
webView.loadUrl("javascript:" + jsHandleGrey());
} else {
// 低于Android 10版本
webView.setDrawingCacheEnabled(true);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.setBackgroundColor(Color.TRANSPARENT);
Paint paint = new Paint();
paint.setColorFilter(filter);
webView.setLayerPaint(paint);
}
}
private String jsHandleGrey() {
return "var style_special = document.createElement('style');\n" +
"var css_special = `* {\n" +
" filter: grayscale(100%) !important;\n" +
" -webkit-filter: grayscale(100%) !important;\n" +
" }`;\n" +
"style_special.appendChild(document.createTextNode(css_special));\n" +
"document.head.appendChild(style_special);";
}
private void nativeHandleGrey(WebView view, ColorMatrixColorFilter filter) {
Bitmap webViewBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(webViewBitmap);
view.draw(canvas);
Paint paint = new Paint();
paint.setColorFilter(filter);
canvas.drawBitmap(webViewBitmap, 0, 0, paint);
if (webViewBitmap != null)
webViewBitmap.recycle();
}
最后,在WebView加載網(wǎng)頁之前,調(diào)用applyGrayscaleFilter()方法以應(yīng)用灰度濾鏡效果:文章來源:http://www.zghlxwxcb.cn/news/detail-646104.html
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
applyGrayscaleFilter();
}
});
webView.loadUrl("https://www.example.com");
這樣就可以在WebView中顯示灰度網(wǎng)頁了。根據(jù)系統(tǒng)版本的不同,使用了不同的濾鏡方法來實(shí)現(xiàn)灰度效果。請注意,這種方法可能會影響WebView的性能和渲染速度,因此請確保在使用之前進(jìn)行足夠的測試。文章來源地址http://www.zghlxwxcb.cn/news/detail-646104.html
到了這里,關(guān)于android webview 顯示灰度網(wǎng)頁的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!