1. 程式人生 > >除去WebView預設存在的一定畫素的邊距問題

除去WebView預設存在的一定畫素的邊距問題

  • 需求:文字編輯器編輯的圖文資訊,圖片顯示的寬度要滿屏。

  • WebView不管怎麼修改它的屬性加載出來的內容都會存在一定的邊距

String data="<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\\\"顯示的圖片" /> ";//資料來源

data = "<head><style>img{ width:100% !important;}</style></head>"+data;//對資料進行包裝

mWebView.loadDataWithBaseURL(null, data, "
text/html", "utf-8", null);//mWebView目標webview

效果圖:有一定的填充
有邊距圖片

  • 如果要去掉這些 body標籤 預設的邊距,需要通過修改HTML標籤的樣式來
String data="<img src=\"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg\" alt=\\\"顯示的圖片" /> ";//資料來源

data="<html><head><style>img{width:
100% !important;}</style></head><body style='margin:0;padding:0'>"+data+"</body></html>"; //對資料進行包裝 mWebView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);//mWebView目標webview

效果圖:已經全屏
這裡寫圖片描述

解析一下里面關鍵的程式碼:

  • 圖片滿屏
<style\>img{width:100% !important;}\</style>
  • 去除body標籤預設的邊距
<body style='margin:0;padding:0'>
  • H5中讓手機載入滿屏的處理,header中這一句程式碼暫時不用
<meta name=\"viewport\"content=\"width=device-width, initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0, user-scalable=no\">